Socket通信
1、TCP通信
服务端:
//新建ServerSocket对象监听8080端口(端口号最好1024-5 0-1023为系统保留端口) ServerSocket serverSocket=new ServerSocket(8080); // Socket socket=serverSocket.accept(); // InputStream is=socket.getInputStream(); // InputStreamReader in=new InputStreamReader(is); BufferedReader reader=new BufferedReader(in); // PrintWriter out=new PrintWriter(socket.getOutputStream()); String str=reader.readLine();
客户端:
Socket socket=new Socket("127.0.0.1",8080); OutputStream outputStream=socket.getOutputStream(); PrintWriter out =new PrintWriter(outputStream); out.println("1:112:123"); out.flush();
2、UDP
服务器:
//DatagramSocket表示接受或发送数据报的套接字(udp) DatagramSocket socket=new DatagramSocket(8181); System.out.println("服务器启动"); while(true){ //存放数据 byte[] buf=new byte[1024]; //新建DatagramPacket用来存放接收到的数据报包 DatagramPacket packet=new DatagramPacket(buf, 0, buf.length); //接收数据 socket.receive(packet); //打印数据 System.out.println(new String(packet.getData())); //打印地址 System.out.println(packet.getAddress()); //打印端口 System.out.println(packet.getPort());
}
客户端:
String msg="你妹的世界末日"; byte[] buf=msg.getBytes(); DatagramPacket packet=new DatagramPacket(buf, buf.length); InetAddress iaddr=InetAddress.getByName("127.0.0.1"); packet.setAddress(iaddr); packet.setPort(8181); DatagramSocket socket=new DatagramSocket(8182); socket.send(packet);