在 Java 中,你可以使用多种方式来实现 UDP 数据的接收。我将为你介绍两种常见的方式:基于原生 Java 套接字(Socket)的实现和使用第三方库 Netty 的实现。
DatagramSocket
对象,用于接收 UDP 数据报。DatagramPacket
对象,用于存储接收到的数据。receive()
方法接收数据,此方法将阻塞直到有数据包到达。DatagramSocket
。import java.net.DatagramSocket;
import java.net.DatagramPacket;
public class UDPServer {
public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket(9876); // 监听端口9876
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
System.out.println("Server listening...");
socket.receive(packet); // 阻塞等待数据接收
String receivedData = new String(packet.getData(), 0, packet.getLength());
System.out.println("Received data: " + receivedData);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Netty 是一个高性能的网络编程库,它提供了简化网络应用开发的工具和组件。
Bootstrap
实例。<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.68.Final</version>
</dependency>
implementation 'io.netty:netty-all:4.1.68.Final'
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
public class UDPServerNetty {
public static void main(String[] args) {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, true)
.handler(new ChannelInitializer<DatagramChannel>() {
@Override
protected void initChannel(DatagramChannel ch) throws Exception {
ch.pipeline().addLast(new UDPHandler());
}
});
bootstrap.bind(9876).sync().channel().closeFuture().await();
} catch (Exception e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
}
}
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
public class UDPHandler extends SimpleChannelInboundHandler<DatagramPacket> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
String receivedData = packet.content().toString(Charset.forName("UTF-8"));
System.out.println("Received data: " + receivedData);
}
}
这两种方法都可以用来实现 UDP 数据的接收,你可以根据你的需求和偏好选择其中之一。