Netty 4.0中如何引导UDP服务器?

6
有人可以为我提供一个Netty 4.0的UDP服务器吗?我看到了很多3.x的例子,但是在netty源码示例中没有4.x版本的迹象。(请注意我对Netty非常陌生)基本上,这就是https://netty.io/Documentation/New+and+Noteworthy#HNewbootstrapAPI中的示例,只不过是针对UDP而言。非常感谢您的帮助。

欢迎来到StackOverflow。请阅读FAQ,特别是关于此处欢迎的问题类型。这个问题可能更适合其他Stack Exchange网站。 - marko
1
这是一个非常适合在SO上提问的问题。 - RockMeetHardplace
检查这个项目,看起来他们正在使用Netty 4和UDP:https://github.com/menacher/java-game-server/blob/netty4/nadron/src/main/java/io/nadron/handlers/netty/UDPUpstreamHandler.java - Alberto Anderick Jr
1个回答

2

netty-example包括类QuoteOfTheMomentServerQuoteOfTheMomentServerHandlerQuoteOfTheMomentClientQuoteOfTheMomentClientHandler。它们演示了如何创建一个简单的UDP服务器。

我将粘贴现有代码Netty 4.1.24版本。建议您在使用的Netty版本中查找这些类。

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();
    }
}
}

时刻引用服务器处理程序:

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.
}
}

嗨@aleksandr-dubinsky,QuoteOfTheMomentServer使用Bootstrap类而不使用ServerBootstrap。如果我使用ServerBootstrap,则在示例中提到的NioDatagramChannel不能被使用,因为它不扩展自ServerChannel。请问您能否解释一下为什么示例使用Bootstrap类,而该类通常用于客户端而非服务器?虽然我理解示例的行为类似于一个服务器。 - garnet
我认为这回答了我的问题。https://dev59.com/Kpfga4cB1Zd3GeqPAsIR#37681245 如果我错了,请纠正我。 - garnet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接