注:在使用以下代码时,需注意在客户端中的IP需要使用运行服务端的电脑IP,且连接时需要在同一个网路下进行,方可成功连接。
服务器端代码:
import java.net.*;
public class Sv {
public static void main(String[] args) throws Exception {
DatagramSocket ds=new DatagramSocket(9898);
byte[] by=new byte[1024];
DatagramPacket dp=new DatagramPacket(by,by.length);//创建一个空的用来接受发送来的数据报的数据报
ds.receive(dp); //接受传来的数据报,同时也装到了构建的数组中
String str=new String(dp.getData(),0,dp.getLength());
System.out.println(str.toUpperCase());
ds.close();
}
}
客户端代码:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
public class Cl {
public static void main(String[] args) throws IOException {
DatagramSocket ds=new DatagramSocket();
byte[] by="我是客户端的信息包hhhhh".getBytes(StandardCharsets.UTF_8);
//将要发送的信息进行打包
DatagramPacket dp=new DatagramPacket(by,0,by.length, InetAddress.getByName("10.13.102.129"),9898);
ds.send(dp); //发送打包好的数据包
ds.close();
}
}