为Netty 4.0增加UDP服务器?

Dan*_*ran 6 netty

有人可以使用UDP服务器为Netty 4.0引导我吗?我看到很多3.x示例,但即使在netty源示例中也没有4.x的迹象.(注意我对Netty很新)

基本上,它是https://netty.io/Documentation/New+and+Noteworthy#HNewbootstrapAPI的示例,但是对于UDP而言.非常感谢帮助

Ale*_*sky 2

包包括netty-exampleQuoteOfTheMomentServerQuoteOfTheMomentServerHandlerQuoteOfTheMomentClientQuoteOfTheMomentClientHandler这些演示了如何创建一个简单的 UDP 服务器。

我粘贴Netty 4.1.24中存在的代码。我建议找到适合您正在使用的 Netty 版本的这些类。

服务器报价:

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();
    }
}
}
Run Code Online (Sandbox Code Playgroud)

报价时刻服务器处理程序:

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.
}
}
Run Code Online (Sandbox Code Playgroud)