How to Fix the Java.Net.SocketException: Connection Reset in Java

Muhammad Zeeshan Feb 02, 2024
  1. the java.net.SocketException in Java
  2. Causes of the java.net.SocketException: Connection reset in Java
  3. Reproduce the java.net.SocketException: Connection reset Error and Identify Its Causes in Java
  4. Fix the java.net.SocketException: Connection reset Error in Java
How to Fix the Java.Net.SocketException: Connection Reset in Java

Today’s article will discuss the reasons for and solutions for the java.net.SocketException: Connection reset error that might occur in Java. Finally, we will see how we can eradicate Java’s java.net.SocketException: Connection reset error.

the java.net.SocketException in Java

SocketException is the subclass of IOException. Its status as a checked exception is guaranteed.

When attempting to open or access a socket, the most generic exception that can occur indicates that there is an issue. You will get the following error if you look at the server’s side:

java.net.SocketException : Connection reset

Causes of the java.net.SocketException: Connection reset in Java

java.net.SocketException: Connection reset is thrown on the server when the client terminates the connection to the socket before the response can be sent back through the socket. Let’s suppose you may close the browser before the response is fetched from the server.

TCP RST packets are the remote side’s way of informing you that the connection on which the last TCP packet was transmitted is not acknowledged. A Connection reset indicates that a TCP RST was successfully received.

This could be because the connection is no longer active. After all, the port is closed or for other reasons.

A simple definition of a Reset packet contains no content and has the RST bit set in the TCP header flags. The following are some of the reasons the java.net.SocketException: Connection reset error can occur:

  1. As a result of receiving a close command from a remote system, the TCP socket has been closed.
  2. This can also be caused by a high amount of requests being queued by the server, which causes the request to be timed-out before the client can view it. You can also check the server’s health and logs to see whether a heavy load is caused.
  3. Closing a socket with unread data in the socket receive buffer can also result in this error.
  4. The connection has been intentionally reset on the other end. While this is rare and inappropriate for application software, commercial software is not uncommon.
  5. Either the application protocol is incorrect, or you tried to write to a connection that had been terminated before you were finished.

Reproduce the java.net.SocketException: Connection reset Error and Identify Its Causes in Java

Example Code (Server.java file):

package com.demobrokenpipe;

import java.io.*;
import java.net.*;

public class Server {
  public static void main(String[] args) throws Exception {
    ServerSocket socket = new ServerSocket(6666);
    System.out.println("The Server Is Initialized");
    Socket conn = socket.accept();
    System.out.println("A Request Is Received");
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    System.exit(1);
    conn.close();
  }
}

Example Code (Client.java file):

package com.demobrokenpipe;

import java.io.*;
import java.net.*;

public class Client {
  public static void main(String argv[]) throws Exception {
    Socket socket = new Socket("localhost", 6666);
    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    out.write("Hi");
    System.out.println("Incorrect String");
    BufferedReader bufferReader =
        new BufferedReader(new InputStreamReader(socket.getInputStream()));
    System.out.println(bufferReader.read());
  }
}

Here, we have two classes, Server.java and Client.java, connecting to the port number 6666. We open two terminals and run both files to communicate between client and server, but it prints a message and an error as follows.

Error Description:

Incorrect String
Exception in thread "main" java.net.SocketException: Connection reset

Let’s understand the error by going through the Socket, SocketException, and SocketException: Connectin reset that will lead to the causes of this error.

We use sockets to make a successful connection in two or more programs to communicate with each other using the same network. In our case, we have two programs, Client.java and Server.java.

By using Sockets, we get an interface to communicate via network protocol stack and let the programs share messages over the same network.

In simple words, we can say that Sockets are the endpoints in communications over a network. Usually, the socket server is multi-threaded that can accept socket connection requests sent by different clients.

The SocketException is the child class of IOException, so it is a checked exception. It occurs when we try to access or open the socket. Have a look at the complete exception hierarchy for SocketException errors.

Full Exception Hierarchy:

Fix Java Net SocketException Connection Reset in java - exception hierarchy

Whenever the client closes the socket connection, it results in SocketException on the server-side because the response was not returned over that socket yet. Yes, you got it right.

We get the java.net.SocketException: Connection reset error on the server side when the client closes the socket connection before receiving the response fully.

Here, Connection reset means the remote endpoint informs you that the connection on which the last TCP packet was sent is not recognized. There can be various reasons for this.

Let’s find them below:

  1. The user closes the web browser before getting the response completely.

  2. Most commonly, the connection we try to write has been closed normally. We can also say that there is an application protocol error.

  3. Another possibility is that the required port is not open anymore. We also see this error when a client closes the socket while unread data is still in a socket receive buffer.

  4. If you are a Windows user, you may find it as software caused a connection abort. The newbies make it confused with Connection reset.

    Remember, both are not the same. The software caused a connection abort occurs when we have some network issues while sending from our end.

  5. Another situation is using a method of Java Socket called setSoTimeout() that enables/disables the SO_TIMEOUT option by passing a timeout value which must be greater than 0. Passing 0 is also a reason that results in the SocketException: Connection Reset error.

Now, the point is that are we also closing the connection in the Client.java file? Let’s find that below.

Fix the java.net.SocketException: Connection reset Error in Java

If we face this error as a client while connecting with the server, we can fix this by doing any of the following:

  1. Make sure the server runs via telnet on a host port. This port is where the server runs.
  2. Confirm if a server is restarted.
  3. Assess if the same server fails over to a different host.

Further, we can move towards the solution if we overcome the reasons described in the previous section. In our case, removing System.exit(1) fixed the error because it was exiting the system and closing the program.

Example Code (Server.java file):

import java.io.*;
import java.net.*;

public class Server {
  public static void main(String[] args) throws Exception {
    ServerSocket socket = new ServerSocket(6666);
    System.out.println("The Server Is Initialized");
    Socket conn = socket.accept();
    System.out.println("A Request Is Received");
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    System.out.println(reader.readLine());
    conn.close();
  }
}

Example Code (Client.java file):

import java.io.*;
import java.net.*;

public class Client {
  public static void main(String argv[]) throws Exception {
    Socket socket = new Socket("localhost", 6666);
    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    out.write("Hi");
    System.out.println("Incorrect String");
    BufferedReader bufferReader =
        new BufferedReader(new InputStreamReader(socket.getInputStream()));
    System.out.println(bufferReader.read());
  }
}
Muhammad Zeeshan avatar Muhammad Zeeshan avatar

I have been working as a Flutter app developer for a year now. Firebase and SQLite have been crucial in the development of my android apps. I have experience with C#, Windows Form Based C#, C, Java, PHP on WampServer, and HTML/CSS on MYSQL, and I have authored articles on their theory and issue solving. I'm a senior in an undergraduate program for a bachelor's degree in Information Technology.

LinkedIn

Related Article - Java Error