/*
UDP协议的网络编程
*/
public class UDPTest {
//发送端
@Test
public void sender(){
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
String str = "我是UDP方式发送的信息";
byte[] data = str.getBytes();
InetAddress inet = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);
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(9090);
byte[] buffer = new byte[100];
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.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-05-20 17:52:36 发布
本文档详细介绍了如何使用Java实现UDP协议的网络编程,包括发送端通过DatagramSocket发送数据到本地主机9090端口,以及接收端监听并打印接收到的数据。适合理解UDP通信原理和进行简单网络应用开发的学习者。
摘要由CSDN通过智能技术生成