java.net.BindException: bind failed: EADDRINUSE (Address already in use)
03:53 19 Nov 2013

I have a service, which starts Thread to perform some operations on socket. The code looks like:

 public class ServerRunnable implements Runnable {
    @Override
    public void run() {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket();
            serverSocket.setReuseAddress(true);
            serverSocket.bind(new InetSocketAddress(ProtocolConstants.USB_SERVER_PORT));
        while (true) {
            Socket client = serverSocket.accept();
            // some code
        } catch (Exception e) {
            Log.e("Exception while listening on socket.", e);
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    Log.e(e);
                }
            }
        }

When I start service first time, everything is ok, but then I have to stop it using stopService method. When I start it one more time it returns following exception:

java.net.BindException: bind failed: EADDRINUSE (Address already in use)

In addition I added ServerSocket closing in onDestroy method of service but it did not help.

The setReuseAddress is performed before bind, so why it is not working?

android sockets network-programming port