I have set up a basic UDP server using netty 4.1 which works fine in reading data from the packets. I would like to add a feature to server to reply to the client upon receiving the UDP packet. What is the best way to go about doing this. I know UDP is a connection-less communication method, but you should be able to obtain the IP address and reply to the client?
My code is as follows;
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();
}
}
Could someone please point me in the right direction in how to obtain the source ip address? Many thanks in advance for your help
The source IP address is in the
DatagramPacket
.