Why sockets does not die when server dies? Why socket dies when server is alive?

Posted by Roman on Stack Overflow See other posts from Stack Overflow or by Roman
Published on 2010-03-17T12:56:29Z Indexed on 2010/03/17 13:11 UTC
Read the original article Hit count: 235

Filed under:
|
|
|

I try to play with sockets a bit. For that I wrote very simple "client" and "server" applications.

Client:

import java.net.*;

public class client {
    public static void main(String[] args) throws Exception {
    InetAddress localhost = InetAddress.getLocalHost();
    System.out.println("before");

    Socket clientSideSocket = null;
    try {
        clientSideSocket = new Socket(localhost,12345,localhost,54321);
    } catch (ConnectException e) {
        System.out.println("Connection Refused");
    }
    System.out.println("after");

    if (clientSideSocket != null) {
        clientSideSocket.close();
    }
    }
}

Server:

import java.net.*;

public class server {
    public static void main(String[] args) throws Exception {
    ServerSocket listener = new ServerSocket(12345);

    while (true) {
        Socket serverSideSocket = listener.accept();
        System.out.println("A client-request is accepted.");
    }

    }
}

And I found a behavior that I cannot explain:

  1. I start a server, than I start a client. Connection is successfully established (client stops running and server is running). Then I close the server and start it again in a second. After that I start a client and it writes "Connection Refused". It seems to me that the server "remember" the old connection and does not want to open the second connection twice. But I do not understand how it is possible. Because I killed the previous server and started a new one!

  2. I do not start the server immediately after the previous one was killed (I wait like 20 seconds). In this case the server "forget" the socket from the previous server and accepts the request from the client.

  3. I start the server and then I start the client. Connection is established (server writes: "A client-request is accepted"). Then I wait a minute and start the client again. And server (which was running the whole time) accept the request again! Why? The server should not accept the request from the same client-IP and client-port but it does!

© Stack Overflow or respective owner

Related posts about java

Related posts about sockets