UDP通讯
发送端:
public static void main(String[] args) throws Exception {
//创建发送端Socket
DatagramSocket sendSocket = new DatagramSocket();
//准备数据
String string = "你好java";
byte[] message = string.getBytes();
int length = message.length;
InetAddress localHost = InetAddress.getLocalHost();
int port = 10088;
//打包数据
DatagramPacket packet = new DatagramPacket(message,length, localHost,port);
//发送数据
sendSocket.send(packet);
sendSocket.close();
}
接收端:
public static void main(String[] args) throws Exception {
int port = 10088;
//创建接收端的socked
DatagramSocket socket = new DatagramSocket(port);
byte[] array = new byte[1024*1];
//接收数据
DatagramPacket packet = new DatagramPacket(array, array.length);
socket.receive(packet);
String string = new String(array,0,array.length);
System.out.println(string);
socket.close();
}
注意:端口号必须相同