2 回答

TA貢獻1998條經(jīng)驗 獲得超6個贊
首先,我假設你使用這個git repo,順便說一下,它寫得很差。此外,我建議不要使用它,因為 UDP 不打算在服務器/客戶端模型中使用,并且 repo 所做的只是管理您的 UDP 通道,這些通道不存在,因為 UDP 是無連接的。它真正做的就是存儲一個假的通道實例,它的核心只是一個InetAddress
. 你可以做的是使用普通線程安全List
或某種存儲來InetAddress
緩存不同的東西,然后使用它。
但是如果你真的需要使用這個 repo,你需要停止ServerChannel
實例,因為它UdpServerChannel
啟動了一個新的事件循環(huán),它不會暴露在外面,只能在關(guān)閉通道時停止。(這是你不應該使用它的另一個原因,EventLoopGroups
為同一件事打開多個是浪費的)

TA貢獻2011條經(jīng)驗 獲得超2個贊
我想我找到了另一種方法來解決這個問題。我的問題的解決方案,它不是完美的,但它做了我想要的。
public class UdpServer {
private int port;
private UDPViewModel viewModel;
private final EventLoopGroup nioEventLoopGroup;
private ChannelFuture channelFuture;
public UdpServer(UDPViewModel viewModel, int port) {
this.port = port;
this.viewModel = viewModel;
nioEventLoopGroup = new NioEventLoopGroup();
}
public void run() {
System.out.println("UDP Server is starting.");
try{
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(nioEventLoopGroup)
.channel(NioDatagramChannel.class)
.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) {
channel.pipeline().addLast(
new LoggingHandler(LogLevel.INFO),
new StringEncoder(), new StringDecoder());
channel.pipeline().addLast(
new UdpServerHandler(viewModel));
}
});
channelFuture = bootstrap.bind(port).sync();
}
catch (InterruptedException e) {
System.err.println("UDP listener was interrupted and shutted down");
e.getCause();
}
}
public void StopServer()
{
try {
nioEventLoopGroup.shutdownGracefully().sync();
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
添加回答
舉報