gpt4 book ai didi

sockets - Netty 允许不同程序多次绑定(bind)同一个端口

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

我是套接字编程的菜鸟。也许我在问一个基本问题。请多多包涵。
我编写了一个示例 netty 服务器并从控制台启动它。它运行良好。我遇到的问题是,当我从两个控制台窗口运行同一服务器时,我希望其中一个会抛出“地址已在使用”异常。它不这样做,我不明白为什么。请帮忙。

    public static void main(String[] args) {
ChannelFactory cf = new NioServerSocketChannelFactory(Executors.newFixedThreadPool(100), new MemoryAwareThreadPoolExecutor(1000,2048,25096,2,TimeUnit.SECONDS));
//ChannelFactory cf = new OioServerSocketChannelFactory(Executors.newFixedThreadPool(100), Executors.newCachedThreadPool());


ServerBootstrap bootstrap = new ServerBootstrap(cf);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {

@Override
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(new ChannelHandler("test"));
}
});

bootstrap.setOption("child.keepAlive", true);
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.reuseAddress", true);
bootstrap.setOption("child.connectTimeoutMillis", 30000);
//NEVER bootstrap.setOption("child.readWriteFair", true);
//bootstrap.setOption("disconnect", true);
bootstrap.setOption("tcpNoDelay", true);
bootstrap.setOption("reuseAddress", true);
bootstrap.setOption("connectTimeoutMillis", 30000);
bootstrap.setOption("readWriteFair", true);
bootstrap.bind(new InetSocketAddress(9998));
}

最佳答案

总结上面的许多评论:
bootstrap.setOption("reuseAddress", true);选项将允许绑定(bind)到已绑定(bind)的 ip:port组合。这通常用于在服务器崩溃/被杀死时重新启动服务器(因此当套接字仍处于 TIME_WAIT 状态时)。

在 Windows 中,可能有两个完全不同的程序绑定(bind)完全相同的 ip:port .因此,即使在您的应用程序中您有 bootstrap.setOption("reuseAddress", false);启用 SO_REUSEADDR 的其他应用程序(即恶意)仍然可能成功绑定(bind)您的ip:port .

更多详情请看这里:http://msdn.microsoft.com/en-us/library/windows/desktop/ms740621(v=vs.85).aspx

关于sockets - Netty 允许不同程序多次绑定(bind)同一个端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12113485/

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