Socketソケットプログラミング
20760 ワード
UDP
サービス側
public static void main(String[] args) throws IOException {
//1. DatagramSocket
DatagramSocket socket=new DatagramSocket(9999);
//
byte[]buffer=new byte[1024];
DatagramPacket packet=new DatagramPacket(buffer,buffer.length);
//2.
//
socket.receive(packet);//
String str=new String(buffer,0,packet.getLength(),"UTF-8");
System.out.println(str);
byte[]arr=" ".getBytes("UTF-8");
DatagramPacket data=new DatagramPacket(buffer,packet.getLength(),packet.getAddress() ,packet.getPort() );
socket.send(data);
}
クライアント
public static void main(String[] args) throws IOException {
DatagramSocket socket=new DatagramSocket();
byte[]buffer=" ".getBytes("UTF-8");
DatagramPacket packet=new DatagramPacket(buffer,buffer.length,InetAddress.getLoopbackAddress() ,9999);
socket.send(packet);
byte[]arr=new byte[1024];
DatagramPacket data=new DatagramPacket(arr,arr.length);
socket.receive(data);
String str=new String(arr,0,data.getLength(),"UTF-8");
System.out.println(str);
}
TCP
サービス側
public static void main(String[] args) throws IOException {
ServerSocket serversocket=new ServerSocket(8888);
Scanner scanner=new Scanner(System.in);
while(true){
Socket socket=serversocket.accept();// ,
System.out.println(" "+socket.getInetAddress().getHostAddress() +":"+socket.getPort() );
InputStream is=socket.getInputStream();
InputStreamReader ism=new InputStreamReader(is,"UTF-8");
BufferedReader reader=new BufferedReader(ism);
OutputStream os=socket.getOutputStream();
PrintStream out=new PrintStream(os,true,"UTF-8");
String sc=reader.readLine();
System.out.println(" :"+sc);
System.out.println(" :");
String response=scanner.nextLine() ;
out.println(response);
socket.close();
}
}
クライアント
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
Socket socket = new Socket();
byte[] arr = {(byte) 127, (byte) 0, (byte) 0, (byte) 1};
InetAddress intadd = InetAddress.getByAddress(arr);
SocketAddress address = new InetSocketAddress(intadd, 8888);
socket.connect(address);
while (true) {
OutputStream os = socket.getOutputStream();
PrintStream out = new PrintStream(os, true, "UTF-8");
String request = scanner.nextLine();
out.println(request);
out.flush();
InputStream is = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String str=reader.readLine();
System.out.println(str);
}
}