How do I unbind a server socket once I call bind()

Trustin Lee tlee at redhat.com
Mon Mar 9 06:32:49 EDT 2009


Hi Virat,

On Mon, Mar 9, 2009 at 7:13 PM, Virat Gohil <virat4lug at gmail.com> wrote:
> I have created a ServerSocketChannelFactory as follows:
>
> factory = new
> NioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool(),numHandlerThreads);
> bootstrap = new ServerBootstrap(factory);
> bootstrap.bind(new InetSocketAddress(PORT));
>
> My question is, how do I unbind the port when shutting down my server.

Shutting down a server is composed of three steps:

1) Close the server socket
2) Close all accepted sockets (i.e. all client connections)
3) Stop the boss and worker threads of ChannelFactory

To implement the three steps, you can use ChannelGroup and
ChannelFactory.releaseExternalResources().

  public class Main {
    // HERE: Create a group that maintains a set of open channels.
    static final ChannelGroup g = new DefaultChannelGroup("myServer");

    public static void main(String[] args) throws Exception {
      ChannelFactory f = new NioServerSocketChannelFactory(
          Executors.newCachedExecutor(), Executors.newCachedExecutor());
      ServerBootstrap b = new ServerBootstrap(f);
      ...
      Channel c = b.bind(...);

      // HERE: Add the server socket to the group.
      g.add(c);

      // TODO: Wait until the server needs to shut down.
      // e.g. while (running()) { .. waitForShutDown(); .. }

      // HERE: Close all connections and server sockets.
      g.close().awaitUninterruptibly();

      // HERE: Shutdown the selector loop (boss and worker).
      f.releaseExternalResources() <-- HERE
    }
  }

  public class MyHandler implements SimpleChannelHandler {
    @Override
    public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) {
      // HERE: Add all accepted channels to the group
      //       so that they are closed properly on shutdown
      //       If the added channel is closed before shutdown,
      //       it will be removed from the group automatically.
      Main.g.add(ctx.getChannel());
    }
    ...
  }

Please note that ServerBootstrap (and ClientBootstrap) is just a
helper class.  Therefore, it merely uses what ChannelFactory provides.
 It doesn't create any resources and therefore there's nothing to
release for a Bootstrap.

HTH,

— Trustin Lee, http://gleamynode.net/




More information about the netty-users mailing list