gpt4 book ai didi

netty - 为 Netty 4.0 引导 UDP 服务器?

转载 作者:行者123 更新时间:2023-12-04 15:59:52 25 4
gpt4 key购买 nike

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

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

最佳答案

套餐netty-example包括类 QuoteOfTheMomentServer , QuoteOfTheMomentServerHandler , QuoteOfTheMomentClient QuoteOfTheMomentClientHandler .这些演示了如何创建一个简单的 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();
}
}
}
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.
}
}

关于netty - 为 Netty 4.0 引导 UDP 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13352697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com