How does java net SocketException Connection reset happen

2.2K    Asked by KevinTaylor in Java , Asked on Jul 26, 2021

We are seeing frequent java.net.SocketException: Connection reset errors in our logs for a component that calls a third party Web service that sends SMS messages.

Our application is written in Java and runs on top of Tomcat 5.5. It was written by contractors who are no longer with us. The current team has no real Java expertise, and we are unsure as to where the Connection reset error is actually coming from, and how to go about debugging.

The issue appears to be completely intermittent, and unrelated to the messages we are attempting to send.

Any suggestions on what the typical causes of this exception might be, and how we might proceed, are welcome.

The whole call stack is included below for completeness.

(com.companyname.mtix.sms is our component)

   java.net.SocketException: Connection reset
        at java.net.SocketInputStream.read(SocketInputStream.java:168)
        at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
        at java.io.BufferedInputStream.read(BufferedInputStream.java:235)
        at org.apache.commons.httpclient.HttpParser.readRawLine(HttpParser.java:77)
        at org.apache.commons.httpclient.HttpParser.readLine(HttpParser.java:105)
        at org.apache.commons.httpclient.HttpConnection.readLine(HttpConnection.java:1115)
        at org.apache.commons.httpclient.HttpMethodBase.readStatusLine(HttpMethodBase.java:1832)
        at org.apache.commons.httpclient.HttpMethodBase.readResponse(HttpMethodBase.java:1590)
        at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:995)
        at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:397)
        at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:170)
        at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:396)
        at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:324)
        at com.companyname.mtix.sms.services.impl.message.SendTextMessage.sendTextMessage(SendTextMessage.java:127)
        at com.companyname.mtix.sms.services.MessageServiceImpl.sendTextMessage(MessageServiceImpl.java:125)
        at com.companyname.mtix.sms.services.remote.MessageServiceRemoteImpl.sendTextMessage(MessageServiceRemoteImpl.java:43)
        at sun.reflect.GeneratedMethodAccessor203.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:585)
        at org.apache.axis.providers.java.RPCProvider.invokeMethod(RPCProvider.java:397)
        at org.apache.axis.providers.java.RPCProvider.processMessage(RPCProvider.java:186)
        at org.apache.axis.providers.java.JavaProvider.invoke(JavaProvider.java:323)
        at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
        at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
        at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
        at org.apache.axis.handlers.soap.SOAPService.invoke(SOAPService.java:453)
        at org.apache.axis.server.AxisServer.invoke(AxisServer.java:281)
        at org.apache.axis.transport.http.AxisServlet.doPost(AxisServlet.java:699)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
        at org.apache.axis.transport.http.AxisServletBase.service(AxisServletBase.java:327)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
        at com.companyname.mtix.sms.http.filters.NoCacheFilter.doFilter(NoCacheFilter.java

Answered by Katherine Gray

The javanet socket exception states that it is thrown to indicate that there is an error in the underlying protocol such as a TCP error.

This javanet SocketException occurs on the server side when the client closed the socket connection before the response could be returned over the socket. In your case it seems that the connection has been closed by the server end of the connection. This could be an issue with the request you are sending or an issue at their end.

To aid debugging you could look at using a tool such as Wireshark to view the actual network packets. Also, is there an alternative client to your Java code that you could use to test the web service? If this was successful it could indicate a bug in the Java code.

As you are using Commons HTTP Client have a look at the Common HTTP Client Logging Guide. This will tell you how to log the request at the HTTP level.



Your Answer

Answer (1)

The java.net.SocketException: Connection reset is a common error in Java networking, indicating that the connection was unexpectedly closed by the remote peer. Here are the typical causes and scenarios where this exception can occur:

Server-Side Issues:

Server Crash: If the server crashes or is restarted, any ongoing connections will be reset.

Server Overload: High load on the server can cause it to drop connections abruptly.

Timeouts: If the server does not respond within a certain time, the connection may be reset.

Network Issues: Problems in the network path, such as intermediate firewalls or proxies resetting the connection.

Client-Side Issues:

Incorrect Configuration: Incorrect settings in the client configuration can lead to connection resets.

Large Data Transfers: Sending very large amounts of data without proper handling can cause timeouts and resets.

Improper Handling of Streams: Not properly closing input/output streams or sockets can lead to exceptions.

Network and Protocol Issues:

TCP Keepalive: TCP keepalive settings can lead to connection resets if the connection appears idle.

Network Glitches: Temporary network issues, such as packet loss or high latency, can cause resets.

Firewalls/Proxies: Intermediate devices like firewalls or proxies can drop connections if they detect unusual activity or policy violations.

How to Handle Connection reset Exception

Retry Mechanism: Implementing a retry mechanism to attempt reconnection can help in transient issues.

Timeouts and Keepalives: Adjusting timeouts and keepalive settings can help maintain connections.

Resource Management: Properly closing sockets and streams to ensure no resource leaks.

Logging and Monitoring: Adding logging and monitoring to detect patterns and diagnose the root cause.

Network Configuration: Ensuring that network configurations are optimized and stable.

Example Code Snippet for Handling Connection Reset

Here's a basic example in Java of how you might handle a SocketException:

import java.io.*;
import java.net.*;
public class SocketClient {
    public static void main(String[] args) {
        String hostname = "example.com";
        int port = 80;
        while (true) {
            try (Socket socket = new Socket(hostname, port);
                 PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                 BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
                // Send request to the server
                out.println("GET / HTTP/1.1");
                out.println("Host: " + hostname);
                out.println("Connection: Close");
                out.println();
                // Read the response from the server
                String responseLine;
                while ((responseLine = in.readLine()) != null) {
                    System.out.println(responseLine);
                }
                break; // Exit the loop if successful
            } catch (SocketException e) {
                if (e.getMessage().equals("Connection reset")) {
                    System.out.println("Connection reset, retrying...");
                    // Optionally, add a delay before retrying
                } else {
                    e.printStackTrace();
                    break; // Exit on other SocketExceptions
                }
            } catch (IOException e) {
                e.printStackTrace();
                break; // Exit on other IOExceptions
            }
        }
    }
}

In this example, the client attempts to connect to a server and handle the Connection reset error by retrying the connection.

5 Months

Interviews

Parent Categories