Skip to content

Enable SO_REUSEADDR

Marcel Prestel edited this page Aug 2, 2017 · 1 revision

Introduction

When a TCP connection is closed the connection may remain in a timeout state for a period of time after the connection is closed (typically known as the TIME_WAIT state or 2MSL wait state). For applications using a well known socket address or port it may not be possible to bind a socket to the required SocketAddress if there is a connection in the timeout state involving the socket address or port.

Enabling SO_REUSEADDR prior to binding the socket using bind(SocketAddress) allows the socket to be bound even though a previous connection is in a timeout state.

The following examples show how to enable SO_REUSEADDR since it is disabled by default!

Keep in mind, you can't enable/disable SO_REUSEADDR when you initiated the connection already.

Enable SO_REUSEADDR for the websocket server

To enable SO_REUSEADDR you have to use the setter provided by the WebsocketServer.

E.g. using the example class ChatServer.

ChatServer s = new ChatServer( port );
s.setReuseAddr( true );
s.start();

You HAVE to use the setter before you start up the websocket server.

Enable SO_REUSEADDR for the websocket client

To enable SO_REUSEADDR for the websocket client you have to use the setter provided by the WebsocketClient.

E.g. using the example class ExampleClient.

ExampleClient c = new ExampleClient( new URI( "ws://localhost:8887" ) );
c.setReuseAddr( true );
c.connect();