首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为Netty 4.0启动UDP服务器?

为Netty 4.0启动UDP服务器?
EN

Stack Overflow用户
提问于 2012-11-12 22:34:53
回答 1查看 10K关注 0票数 6

有人能用Netty4.0的UDP服务器引导我吗?我看到了大量的3.x示例,但即使在netty源示例中也没有4.x的迹象。(注:我对Netty非常陌生)

基本上,这是https://netty.io/Documentation/New+and+Noteworthy#HNewbootstrapAPI的例子,但却适用于UDP。我们非常感谢你的帮助。

EN

回答 1

Stack Overflow用户

发布于 2018-05-13 10:14:07

netty-example包括类QuoteOfTheMomentServerQuoteOfTheMomentServerHandlerQuoteOfTheMomentClientQuoteOfTheMomentClientHandler。这些演示了如何创建简单的UDP服务器。

我粘贴代码,因为它存在于Netty 4.1.24中。我建议为您正在使用的Netty版本找到这些类。

QuoteOfTheMomentServer:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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.
}
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13352697

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档