5

I am trying to reproduce "java.net.SocketException.Connection reset" exception.

Wanted to know if there is any program available which could help me simulate it. I tried following Server and client programs to see if I could simulate but I am not able to get any exception. I am using java8.

Server Code-

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;


public class SimpleServerApp {

    public static void main(String[] args) throws InterruptedException {

        new Thread(new SimpleServer()).start();

    }

    static class SimpleServer implements Runnable {

        @Override
        public void run() {

            ServerSocket serverSocket = null;

            try {
                serverSocket = new ServerSocket(3333);
                serverSocket.setSoTimeout(0);

                //serverSocket.
                while (true) {
                    try {
                        Socket clientSocket = serverSocket.accept();

                        BufferedReader inputReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

                        System.out.println("Client said :"+ inputReader.readLine());

                    } catch (SocketTimeoutException e) {
                        e.printStackTrace();
                    }
                }

            }catch (Exception e) {
                e.printStackTrace();
                System.out.println(" EXCEPTION " + e.getStackTrace());
            }/*catch (IOException e1) {
                e1.printStackTrace();
            }*/ /*finally {
                try {
                    if (serverSocket != null) {
                        serverSocket.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }*/

        }

    }
}

Client Code -

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;


public class SimpleClientApp {

    public static void main(String[] args) {

        new Thread(new SimpleClient()).start();

    }

    static class SimpleClient implements Runnable {

        @Override
        public void run() {

            Socket socket = null;
            try {

                socket = new Socket("localhost", 3333);


                PrintWriter outWriter = new PrintWriter(socket.getOutputStream(), true);

                System.out.println("Wait");

                Thread.sleep(20000);
                //System.exit(0);
                //throw new Exception("Random exception");
                //socket.close();

                outWriter.println("Hello Mr. Server!");

            }catch (SocketException e) {
                e.printStackTrace();
            }catch (InterruptedException e) {
                e.printStackTrace();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } /*finally {

                try {
                    if (socket != null)
                        socket.close();
                } catch (IOException e) {

                    e.printStackTrace();
                }


            }
*/      }

    }

}

Scenario 1.

  • Start the server program locally.
  • Start the Client program locally.
  • Close the client program abruptly (Ctrl C) - I just get output on Server program "Client said :null"

Scenario 2.

  • Start the Server program Locally.
  • Start the client program locally.
  • Client is connected to server, Then while client program is waiting close the server program abruptly. Still no exception.

Can some tell me some way I could produce the connection reset exception, With working sample code.

5 Answers 5

10

None of the answers above worked for me reliably both on Mac and Linux. After a lot of Googling, I ended with this article explaining how to do it. Just to be clear: I was trying to reproduce the connection reset from the client side, i.e. "Connection reset by peer".

I tried bringing up a process which run netcat, and abruptly killing the process - that only worked on Mac.

I tried socket.close from another thread, same thread - nothing worked.

Simply, all those methods didn't cause the client to send RST to the server, which causes the exception (reset by peer).

The following worked:

  • Setup any server - in my case Netty (their getting started Discard server will do).
  • Use the following client code:
final Socket socket = new Socket("localhost", port);;
socket.setSoLinger(true, 0);
final OutputStream outputStream = socket.getOutputStream();
for (int i=0; i <= 500; i++) {
    outputStream.write('a');
}
outputStream.write('\n');
outputStream.flush();
socket.close();

Thread.sleep(2000);

The soLinger() was the magic trick. According to the Oracle article cited above, when you call socket.close() it sends a RST to the other side, instead of sending FIN and then waiting for the other side to finish reading what ever was sent until the FIN - i.e. force close.

It took me 1 day of work to find this out, so I hope it will save you time on your work.

Sign up to request clarification or add additional context in comments.

Comments

2

There are several ways. I won't post one of them as it is too much abused, but the simple ways to produce it are:

  1. Close a socket immediately you acquire it, without reading anything. This works if the sender is sending to you rather than reading from you.
  2. If you know the sender has sent something, close the socket without reading it in any way.

Comments

2

I managed to reproduce it, by setting the soLinger to true and waiting for one second before closing the connection:

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {
    public static void main(String[] args) {
        final int PORT = 5500;

        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("Server listening on port " + PORT);

            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("New client from " + clientSocket.getInetAddress() + ":" + clientSocket.getPort());
                Thread.sleep(1000); // Sleep for 1 second
                clientSocket.setSoLinger(true, 0);
                clientSocket.close();
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Found this solution in this article: Troubleshooting java.net.SocketException Connection reset

Comments

1

This works for me:

class Server {

    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(9999);
        Socket s = ss.accept();
        InputStream i = s.getInputStream();
        i.read();
    }
}

client connects and disconnects without closing socket

class Client {

    public static void main(String[] args) throws Exception {
        Socket s = new Socket("localhost", 9999);
    }
}

this results in exception on server

Exception in thread "main" java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at net.Server.main(Server.java:13)

3 Comments

I tired your server program, but I did not get any exception. I even tried modifying it like this public class AnotherServer { public static void main(String[] args) throws Exception { try { ServerSocket ss = new ServerSocket(9999); Socket s = ss.accept(); InputStream i = s.getInputStream(); i.read(); } catch (Exception e) { e.printStackTrace(); System.out.println(" THE EXCEPTION " + e.getStackTrace()); } } } But still I am not able to get the exception. I am using mac and java8 incase if that helps
This is platform-dependent. Windows behaves like this. I don't think Unix does.
Here is what I tried 1. Server program running on Mac , Client program running on Windows then I run @Evgeniy Dorofeev's program I could see the connection reset exception on Mac. 2. I run Server program on Windows, and Client program on Mac, I do not see the connection Reset Exception. I think I am just going to try another scenario on Linux to double check if any connection reset exception comes. But I think exception coming is platform dependent.
-1

Instead of provoking this exception using Java client code, I found it easier to just write a short Python script:

import struct, socket
s = socket.socket(socket.AF_INET6)
s.connect(("::1", 8000))
s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 0))
s.close() # provokes Connection Reset at host

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.