我已经使用 netty 4.1 设置了一个基本的 UDP 服务器,它可以很好地从数据包中读取数据。我想向服务器添加一项功能,以便在收到 UDP 数据包后回复客户端。执行此操作的最佳方法是什么?我知道UDP是一种无连接的通信方式,但是你应该能够获取IP地址并回复客户端?
我的代码如下;
public final class Server {
private static final int PORT = Integer.parseInt(System.getProperty("port", "6565"));
public static void runCommand () throws Exception {
System.out.print("Server is started on port = "+PORT+"\n");
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioDatagramChannel.class)
.handler(new ServerHandler());
b.bind(PORT).sync().channel().closeFuture().await();
} finally {
group.shutdownGracefully();
}
}
}
public class ServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
@Override
public void channelRead0 (ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
System.err.println ("Messaged received on " + new Date() + ":\r");
System.err.println(packet.content().toString(CharsetUtil.UTF_8) + "\r\n");
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
有人可以指出我如何获取源 IP 地址的正确方向吗?非常感谢您的帮助
最佳答案
用途:
packet.sender().getAddress()
关于java - 获取数据报包的源IP地址 UDP Netty 4.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41370033/