Boostraping UDP Server for Netty 4.0?

Can someone upload me with a UDP server for Netty 4.0? I see many examples of 3.x, but no signs of 4.x even in the example of a net source. (note that I'm very new to Netty)

Basically, this is an example of https://netty.io/Documentation/New+and+Noteworthy#HNewbootstrapAPI , but UDP is used instead. Help is much appreciated

+6
source share
1 answer

The netty-example package includes the QuoteOfTheMomentServer , QuoteOfTheMomentServerHandler , QuoteOfTheMomentClient and QuoteOfTheMomentClientHandler . They demonstrate how to create a simple UDP server.

I embed the code as it exists in Netty 4.1.24. I suggest finding these classes for the version of Netty you are using.

QuoteOfTheMomentServer:

 public final class QuoteOfTheMomentServer { private static final int PORT = Integer.parseInt(System.getProperty("port", "7686")); public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(new QuoteOfTheMomentServerHandler()); b.bind(PORT).sync().channel().closeFuture().await(); } finally { group.shutdownGracefully(); } } } 

QuoteOfTheMomentServerHandler:

 public class QuoteOfTheMomentServerHandler extends SimpleChannelInboundHandler<DatagramPacket> { private static final Random random = new Random(); // Quotes from Mohandas K. Gandhi: private static final String[] quotes = { "Where there is love there is life.", "First they ignore you, then they laugh at you, then they fight you, then you win.", "Be the change you want to see in the world.", "The weak can never forgive. Forgiveness is the attribute of the strong.", }; private static String nextQuote() { int quoteId; synchronized (random) { quoteId = random.nextInt(quotes.length); } return quotes[quoteId]; } @Override public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception { System.err.println(packet); if ("QOTM?".equals(packet.content().toString(CharsetUtil.UTF_8))) { ctx.write(new DatagramPacket( Unpooled.copiedBuffer("QOTM: " + nextQuote(), CharsetUtil.UTF_8), packet.sender())); } } @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); // We don't close the channel because we can keep serving requests. } } 
0
source

All Articles