Sam YC
Sam YC

Reputation: 11617

Java TCP re-tranmission timeout

public static void main(String args[]){

    byte[] message = ...
    Socket socket = ...
    DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());

    dOut.write(message);  //#1

    dOut.close();
    socket.close();
}

Let's assume that the line #1 will put the data into buffer waiting to flush to remote machine. After that the stream and socket are closed.

We assume that, in the sending process, there is some unknown problem happens in network, and our operating system will resend the packet that was in the buffer until the TCP re-tranmission timeout.

I am wondering that how I can catch this exception in Java program? Because the code above already send out data to buffer and probably closed the stream and socket (and probably exit the Java main body), left all the other job (TCP-related, re-tranmission) to operating system.

My question is, will the TCP re-tranmission (we assume packet lost) continue even Java program exit? What is the best method to catch the re-tranmission timeout error?

Upvotes: 1

Views: 2184

Answers (1)

David Schwartz
David Schwartz

Reputation: 182769

TCP will continue to try to cleanly shutdown the connection even after the program exits. It is generally recommended that the application perform the shutdown itself. Basically, you perform the following sequence of steps:

  1. Shutdown the TCP connection in the send direction triggering the normal close sequence. If the protocol prohibits the other side from sending any data, you can shutdown the connection in the receive direction as well, however, if you do this and the other side sends any data, it may cause the other side to detect an abnormal shutdown as the data it sent will be lost.

  2. Continue to read from the connection until you detect a clean or abnormal shutdown from the other end. If all goes well, you will detect a clean shutdown as soon as you finish receiving any data the other side has sent.

  3. Close the handle or delete the object/reference to the connection. The actual TCP connection is already shut down.

Upvotes: 2

Related Questions