Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket EADDRINUSE (Address already in use)

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.

like image 763
morya Avatar asked Jul 07 '14 16:07

morya


1 Answers

While other answers pointed out the importance of setReuseAddress(true), another problem that could arise is to construct the ServerSocket twice and call bind with the same parameters. For example if you call twice the code run() of the question, serverSocket will be assigned to a new instance of the ServerSocket class, but the old one is still living until garbage collected. Now constructing with the port value as parameter equals to bind the ServerSocket object, and you are going to end up with two ServerSocket bound to the same address, which is forbidden hence the exception. So build your serverSocket with your chosen port only once!

like image 110
AndrewBloom Avatar answered Sep 18 '22 03:09

AndrewBloom