编写代码
实现客户端的代码
public class Woi {
public static void main(String[] args) throws IOException {
//定义要发送的内容,并将字符串转换成字节数组
byte[] by = "发多少哦阿尔法".getBytes();
//将内容数据打包处理
InetAddress id = InetAddress.getByName("localhost");
DatagramPacket dp = new DatagramPacket(by, by.length, id,9800);
//发送数据包
DatagramSocket ds = new DatagramSocket();
ds.send(dp);
}
}
实现服务端的代码
public class Poi {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket(9800);
byte[] b = new byte[1024];
DatagramPacket dp = new DatagramPacket(b, b.length);
ds.receive(dp);
String st = new String(b,0,dp.getLength());
System.out.println(st);
}
}