Socket EADDRINUSE (Address already in use)
android, sockets
Solution
You have to call `setReuseAddress(true)` before the socket is bound to the port. You are calling it after, because you are passing the port to the constructor, which will bind the socket immediately.
Try this instead:
serverSocket = new ServerSocket(); // <-- create an unbound socket first
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(SERVER_PORT)); // <-- now bind it
Problem
I am doing socket programming. I took reference from below link: http://examples.javacodegeeks.com/android/core/socket-core/android-socket-example/ Below is detail about my issue. I have created Android lib for this ServerThread (my project requirement), and this is used in test app. Now test app connect to this through lib and do the process. First time it works perfectly fine, but if I closed and reopen it crashed with exception: "EADDRINUSE (Address already in use)" Also tried `serverSocket.setReuseAddress(true)` this but no luck. My code: ``` public void run() { Socket socket = null; try { serverSocket = new ServerSocket(SERVER_PORT); serverSocket.setReuseAddress(true); } catch (IOException e) { Log.e(TAG, "exception1= " + e.getMessage()); } while (!Thread.currentThread().isInterrupted()) { try { socket = serverSocket.accept(); Log.d(TAG, "server Connected.......!!!!"); communicationThread = new CommunicationThread( socket); commThread = new Thread(communicationThread); commThread.start(); } catch (IOException e) { Log.e(TAG, "exception 2=" + e.getMessage()); } } } ``` If I call `serverSocket.close()` I am getting exception 2 as server socket close. Communication thread is same as given in previous link.