public class UdpTest {
@Test
public void sender(){
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
String str = "UDP方式发送消息";
byte[] bytes = str.getBytes();
InetAddress host = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, host, 9091);
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null){
socket.close();
}
}
}
@Test
public void receiver() {
DatagramSocket socket = null;
try {
socket = new DatagramSocket(9091);
byte[] bytes = new byte[100];
DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
socket.receive(packet);
System.out.println(new String(packet.getData(),0,packet.getLength()));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
socket.close();
}
}
}
}
使用UDP通信案例:发送端发送消息,接收端接受消息将数据显示在控制台上
最新推荐文章于 2022-12-13 15:25:42 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)