Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reproduce tcp CLOSE_WAIT state with java client/server

Is there an easy way to reproduce the tcp CLOSE_WAIT state with a java program?

I have a legacy java application that have this problem and I'd like to be able to reproduce it so that i can test my fix.

Thanks

like image 356
Jeff Avatar asked Apr 18 '13 08:04

Jeff


People also ask

What is TCP CLOSE_WAIT state?

CLOSE_WAIT - Indicates that the server has received the first FIN signal from the client and the connection is in the process of being closed. This means the socket is waiting for the application to execute close() . A socket can be in CLOSE_WAIT state indefinitely until the application closes it.

What happens if there are many Close_wait on a socket?

The CLOSE_WAIT state indicates that the remote end of the connection has finished transmitting data and that the remote application has issued a close(2) or shutdown(2) call. The local TCP stack is now waiting for the local application that owns the socket to close(2) the local socket as well.


1 Answers

A connection is in the CLOSE_WAIT state when the other side has closed the connection but this side hasn't. It is easy to reproduce:

// Client.java (will sleep in CLOSE_WAIT)
import java.io.*;
import java.net.*;

public class Client
{
    public static void main(String[] args) throws Exception
    {
        Socket socket = new Socket(InetAddress.getByName("localhost"), 12345);
        InputStream in = socket.getInputStream();
        int c;
        while ((c = in.read()) != -1)
        {
            System.out.write(c);
        }
        System.out.flush();

        // should now be in CLOSE_WAIT
        Thread.sleep(Integer.MAX_VALUE);
    }
}

// Server.java (sends some data and exits)
import java.io.*;
import java.net.*;

public class Server
{
    public static void main(String[] args) throws Exception
    {
        Socket socket = new ServerSocket(12345).accept();
        OutputStream out = socket.getOutputStream();
        out.write("Hello World\n".getBytes());
        out.flush();
        out.close();
    }
}
like image 188
tom Avatar answered Sep 28 '22 09:09

tom