UDP客户端(发送)
public class UdpClient {
public static void main(String[] args) throws Exception {
//创建发送方Socket,8888为端口
DatagramSocket client = new DatagramSocket(8888);
//准备数据封装成DatagramPacket
String data="test";//需要发送的数据
byte[] datas=data.getBytes();//转化为字节数组
DatagramPacket datagramPacket=new DatagramPacket(datas, datas.length, new InetSocketAddress("localhost", 9999));//9999为接收方端口号
//发送
client.send(datagramPacket);
client.close();
}
}
UDP服务端(接收)
public class Udp_Server {
public static void main(String[] args) throws Exception {
//创建Socket
DatagramSocket server=new DatagramSocket(9999);
//创建接受容器
byte[] container=new byte[1024*60];
//封装成DatagramPacket
DatagramPacket datagramPacket = new DatagramPacket(container, container.length);
//接受数据
server.receive(datagramPacket);
//处理数据
System.out.println(new String(datagramPacket.getData()));
server.close();
}
}