Search code examples
javaclient-serverserversockettcp

How telnet closes tcp connection?


I wrote a simple tcp server in java(Socket) and connect to it via telnet. Everything works properly. I just want to clarify one thing about tcp protocol. If I stop my server in improper way(just push stop in IntelligIdea during execution), I see a message in a client prompt: connection was lost. So, the question is: does server send any information to the client before it crashes? Or telnet and server all the time send some information that I don't know to each other to be sure that connection exists, even if I don't send anything?Or it has to do with tcp protocol? In a nutshell: how does the client know that server crashed? I'm new to it so I decided to clear it up here. Thank you in advance!


Solution

  • The connection runs over TCP. The TCP protocol specifies how a connection gets closed.

    1. The closing side (server) OS detects that the process ended without closing the socket, and initiates the socket closing process.
    2. The server sends a FIN packet to the client
    3. The the client protocol stack receives the FIN and notifies the socket user (telnet) that the connection is closing, and sends an ACK to the server.
    4. The server receives the ACK and goes into a state waiting for the client to send FIN.
    5. When the client program (telnet) acknowledges the closing to the OS, the client protocol stack sends a FIN packet to the server.
    6. The server receives the FIN and terminates and cleans up its side of the connection, and responds with ACK.
    7. The client receives the ACK and terminates and cleans up its side of the connection.

    All of this happens at the OS level, below the JVM or client program and other than the notification to the telnet client that the socket is closing, is invisible. You can find much more detail on the TCP protocol on the web in many, many places.