Netty allows same port to be bound multiple times by different programs

I'm a noob to Sockets Programming.Maybe am asking a fundamental question. Please bear with me. I wrote a sample netty server and started it from console. It runs fine. The problem i have is that when i run the same server from two console windows, i'd expect one of them to throw 'Address already in use' exception. It does not do that and I dont understand why. Please help.

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

To sum up the many comments above:

The bootstrap.setOption("reuseAddress", true); option will allow binding to an already bound ip:port combination. This is usually used to be able to restart a server if it crashed/got killed (so while the socket is still in the TIME_WAIT state).

In Windows it is possible to have two completely different programs bind the exact same ip:port . So even if in your app you have bootstrap.setOption("reuseAddress", false); it is still possible for another app (ie malicious) that enables SO_REUSEADDR to succesfully bind on your ip:port .

See here for more details: http://msdn.microsoft.com/en-us/library/windows/desktop/ms740621(v=vs.85).aspx

链接地址: http://www.djcxy.com/p/11114.html

上一篇: SqliteDataReader在sqlite中的位置

下一篇: Netty允许同一个端口被不同的程序绑定多次