发送端
import java.io.IOException;
import java.net.*;
public class UDPSend {
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket = new DatagramSocket();
byte[] bytes = "hello,upd,我来了".getBytes();
int length = bytes.length;
InetAddress address = InetAddress.getByName("192.168.121.1");
int port = 10086;
DatagramPacket datagramPacket = new DatagramPacket(bytes, length, address, port);
datagramSocket.send(datagramPacket);
datagramSocket.close();
}
}
接收端
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPReceive {
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket = new DatagramSocket(10086);
byte[] bytes = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
datagramSocket.receive(datagramPacket);
byte[] datas = datagramPacket.getData();
int length = datagramPacket.getLength();
String dataString = new String(datas,0,length);
System.out.println("数据是:"+dataString);
datagramSocket.close();
}
}