Allowing only a single persistent connection
Trustin Lee
tlee at redhat.com
Wed Apr 22 02:45:44 EDT 2009
Hi Bob,
On Wed, Apr 22, 2009 at 7:56 AM, Bob Bucy <bob.bucy at gmail.com> wrote:
>
> I'm looking at how to implement a service that allows only a single server
> connection. In other words, upon accepting a connection, I would like to
> close the listener channel (e.g. NioServerSocketChannel); thus, any new
> attempts to connect to my service would immediately be rejected.
>
> Upon losing the connection with the accepted socket channel (e.g.
> NioAcceptedSocketChannel), I then would want to start listening for
> connections again.
>
> Right now, I am calling the NIOServerSocketChannel.close() method in my
> handlers channelConnected method, and calling ServerBootstrap.bind()
> connection in my handler's channelDisconnected() method. This seems to
> work, thinking the close() totally shuts down the Boss thread, and the
> bind() starts it back up.
>
> Does this make sense or am I heading towards disaster.
I would suggest you to unbind sooner because channelConnected() is
called by different thread than the Boss thread, which can lead your
application to a race condition where another connection is accepted
before ServerSocketChannel.close() is called.
A good place to call ServerSocketChannel.close() is
ChannelPipelineFactory.getPipeline(). It is called by the Boss
thread, so there's no risk of the race condition. Please let me know
if my suggestion works. If it doesn't work, it is a bug.
— Trustin Lee, http://gleamynode.net/
More information about the netty-users
mailing list