//接收数据
import java.net.*;
public class UDPTestServer
{
public static void main(String[] args) throws Exception
{
byte[] buffer = new byte[8192];
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
DatagramSocket server = new DatagramSocket(5678);
server.receive(dp);
String s = new String(dp.getData(),dp.getOffset(),dp.getLength());
System.out.println(s);
}
}
//发送数据
import java.io.IOException;
import java.net.*;
public class UDPTestClient {
public static void main(String[] args) throws IOException {
String s="This is just a test";
byte[] buf = s.getBytes();
InetAddress add = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket(buf,buf.length,add,5678);
DatagramSocket theSocket = new DatagramSocket();
theSocket.send(dp);
}
}
本文提供了一个简单的UDP协议客户端和服务端的Java实现案例。服务端监听5678端口接收消息,客户端向该端口发送测试字符串。示例展示了如何使用DatagramSocket、DatagramPacket进行网络通信。

1万+

被折叠的 条评论
为什么被折叠?



