【问题标题】:Multiple Socket Servers in single netty server单个 netty 服务器中的多个 Socket 服务器
【发布时间】:2020-12-12 23:30:33
【问题描述】:

我正在尝试开发支持 TCP 套接字和 WebSockets 的套接字服务器。我用它们的通道和处理程序创建了两个 ServerBootsrap。我用不同的端口启动它们(跳过不必要的代码部分,因为它们工作正常)

...
ChannelFuture channelFuture = serverBootstrap.bind(port);
...
...
ChannelFuture channelFutureWebsocket = serverBootstrapWebSocket.bind(webSocketPort);

在我看过的教程中,它们都以serverBootstrap.bind(port).sync(); 结尾,但如果我以sync 结尾,服务器会停止并等待数据包,并且我无法启动其他服务器(如预期的那样)。如果我不以同步结束,服务器运行正常,但我怀疑它是否会在未来导致错误。

如果我跳过sync()的方法是错误的,我该如何同时运行2个不同的服务器?

【问题讨论】:

    标签: java sockets websocket server netty


    【解决方案1】:

    Future.sync 上的 javadoc 说:“等待这个未来,直到它完成,如果这个未来失败,则重新抛出失败的原因。”

    所以你想要做的是获得两个期货并等待它们,而不是在你甚至有机会绑定第二个服务器之前等待第一个未来。

    等待 2 个期货的简单方法是使用 while 循环并使用非阻塞方法检查两个期货

    ChannelFuture bindFuture1 = bootstrap1.bind(port);
    ChannelFuture bindFuture2 = bootstrap2.bind(port);
    
    while (!bindFuture1.isDone() && !bindFuture2.isDone()) Thread.Sleep(INTERVAL);
    
    //Evaluate both futures to see if there were any errors, wait for the other future to be done or do whatever else you need to based on your requirements.
    

    我建议您阅读 futures 以了解 sync 方法的作用以及为什么它是必要的。也看看这里:Waiting on a list of Future

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-16
      • 2020-10-14
      相关资源
      最近更新 更多