UDP
类似发短信,可以直接往目的发送,而不需要先建立连接。
发送方
DatagramSocket datagramSocket = new DatagramSocket();
InetAddress byName = InetAddress.getByName("127.0.0.1");
String msg = "Hello World!";
DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(),0,msg.length(),byName,8888);
datagramSocket.send(datagramPacket);
datagramSocket.close();
接收方
DatagramSocket datagramSocket = new DatagramSocket(8888);
byte[] bytes = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length);
datagramSocket.receive(datagramPacket);
System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));
datagramSocket.close();
知是行之始,行是知之成
|