Open In App

java.net.SocketException in Java with Examples

Improve
Improve
Like Article
Like
Save
Share
Report

SocketException is a subclass of IOException so it’s a checked exception. It is the most general exception that signals a problem when trying to open or access a socket. The full exception hierarchy of this error is:

java.lang.Object
     java.lang.Throwable
         java.lang.Exception
             java.io.IOException
                 java.net.SocketException

As you might already know, it’s strongly advised to use the most specific socket exception class that designates the problem more accurately. It is also worth noting that SocketException, usually comes with an error message that is very informative about the situation that caused the exception.

Implemented Interfaces: Serializable
Direct Known Subclasses: BindException, ConnectException, NoRouteToHostException, PortUnreachableException

What is socket programming?

It is a programming concept that makes use of sockets to establish connections and enables multiple programs to interact with each other using a network. Sockets provide an interface to establish communication using the network protocol stack and enable programs to share messages over the network. Sockets are endpoints in network communications. A socket server is usually a multi-threaded server that can accept socket connection requests. A socket client is a program/process that initiates a socket communication request.

java.net.SocketException: Connection reset
 

This SocketException occurs on the server-side when the client closed the socket connection before the response could be returned over the socket. For example, by quitting the browser before the response was retrieved. Connection reset simply means that a TCP RST was received. TCP RST packet is that the remote side telling you the connection on which the previous TCP packet is sent is not recognized, maybe the connection has closed, maybe the port is not open, and something like these. A reset packet is simply one with no payload and with the RST bit set in the TCP header flags.

Now as of implementation it is clear that we need two programs one handling the client and the other handling the server. They are as follows: 

Example 1: Server-side 

Java




// Java Program to Illustrate SocketException
// Server Side App
 
// Importing required classes
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
 
// Main class
public class SimpleServerApp {
 
    // Main driver method
    public static void main(String[] args)
        throws InterruptedException
    {
 
        new Thread(new SimpleServer()).start();
    }
 
    static class SimpleServer implements Runnable {
 
        // run() method for thread
        @Override public void run()
        {
 
            ServerSocket serverSocket = null;
 
            // Try block to check for exceptions
            try {
 
                serverSocket = new ServerSocket(3333);
                serverSocket.setSoTimeout(0);
 
                // Till condition holds true
                while (true) {
 
                    try {
                        Socket clientSocket
                            = serverSocket.accept();
 
                        // Creating an object of
                        // BufferedReader class
                        BufferedReader inputReader
                            = new BufferedReader(
                                new InputStreamReader(
                                    clientSocket
                                        .getInputStream()));
 
                        System.out.println(
                            "Client said :"
                            + inputReader.readLine());
                    }
 
                    // Handling the exception
                    catch (SocketTimeoutException e) {
 
                        // Print the exception along with
                        // line number
                        e.printStackTrace();
                    }
                }
            }
 
            // Catch block to handle the exceptions
            catch (IOException e1) {
 
                // Display the line where exception occurs
                e1.printStackTrace();
            }
 
            finally {
 
                try {
                    if (serverSocket != null) {
                        serverSocket.close();
                    }
                }
                catch (IOException e) {
 
                    e.printStackTrace();
                }
            }
        }
    }
}


 
 

Example 2: Client-side 

 

Java




// Java Program to Illustrate SocketException
// Client Side App
 
// Importing required classes
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
 
// Class 1
// Main class
public class SimpleClientApp {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Calling inside main()
        new Thread(new SimpleClient()).start();
    }
 
    // Class 2
    // Helper class
    static class SimpleClient implements Runnable {
 
        // run() method for the thread
        @Override public void run()
        {
 
            // Initially assign null to our socket to be
            // used
            Socket socket = null;
 
            // Try block to e=check for exceptions
            try {
 
                socket = new Socket("localhost", 3333);
 
                // Creating an object of PrintWriter class
                PrintWriter outWriter = new PrintWriter(
                    socket.getOutputStream(), true);
 
                // Display message
                System.out.println("Wait");
 
                // making thread to sleep for 1500
                // nanoseconds
                Thread.sleep(15000);
 
                // Display message
                outWriter.println("Hello Mr. Server!");
            }
            // Catch block to handle the exceptions
 
            // Catch block 1
            catch (SocketException e) {
 
                // Display the line number where exception
                // occurred using printStackTrace() method
                e.printStackTrace();
            }
 
            // Catch block 2
            catch (InterruptedException e) {
                e.printStackTrace();
            }
 
            // Catch block 3
            catch (UnknownHostException e) {
                e.printStackTrace();
            }
 
            // Catch block 4
            catch (IOException e) {
                e.printStackTrace();
            }
 
            finally {
 
                try {
 
                    // If socket goes NULL
                    if (socket != null)
 
                        // Close the socket
                        socket.close();
                }
                catch (IOException e) {
 
                    e.printStackTrace();
                }
            }
        }
    }
}


 
 

Output:

 

java.net.SocketException: Connection reset

at java.net.SocketInputStream.read(SocketInputStream.java:196)

at java.net.SocketInputStream.read(SocketInputStream.java:122)

at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)

at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)

at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)

at java.io.InputStreamReader.read(InputStreamReader.java:184)

at java.io.BufferedReader.fill(BufferedReader.java:154)

at java.io.BufferedReader.readLine(BufferedReader.java:317)

at java.io.BufferedReader.readLine(BufferedReader.java:382)

at com.javacodegeeks.core.lang.NumberFormatExceptionExample.SimpleServerApp$SimpleServer.run(SimpleServerApp.java:36)

at java.lang.Thread.run(Thread.java:744)

 

Now in order to get rid off of the java.net.SocketException to get proper output then it can be perceived via as if you are a client and getting this error while connecting to the server-side application then append the following changes as follows:

 

  1. First, check if the Server is running by doing telnet on the host port on which the server runs.
  2. Check if the server was restarted
  3. Check if the server failed over to a different host
  4. log the error
  5. Report the problem to the server team

Note: In most cases, you will find that either server is not running or restarted manually or automatically.

 



Last Updated : 12 Nov, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads