How to Handle the Socket Exception in Java
Tags: java, development, coding, vscode
Published: 2023-08-06 17:29:17

Java is a powerful and secure programming language used by developers in web development, and app development. Being a programming language, it is subject to runtime exceptions. These exceptions can be handled to make the code run smoothly. SocketException is a subclass of IO Exception. As the name suggests, it is an exception thrown to show that an error has occurred while creating or accessing the socket. It is a type of exception that needs to be dealt with in a specific way called "throwing" or "handling" using a special code structure called a try-catch block.

In this article, users will get an idea about SocketException in Java, its causes, and how to handle it.

Common Reasons For SocketException
The most frequent cause of SocketException in Java is reading or writing to or from a closed socket
Another reason for this is the termination of the connection before the data has been read into the socket buffer. Several other reasons for SocketException are pointed out below:
-	Firewall Intervention
-	Slow Network 
-	Long Idle Connection
-	Application Error

Firewall Intervention
Network Firewall can terminate the socket connections. If you have any firewall installed try turning it off and then check if the problem has been solved.

Slow Network
Slow Network can be the reason for the SocketException. To tackle the specified problem, extend the connection duration limit. This can greatly reduce the SocketException for slow connections using the following code:

```
socket.setSoTimeout(40000); // timeout set to 40,000 ms

```
Long Idle Connection
Another reason for the SocketException can be the long idle connection. It can be terminated from other ends to save resources. The solution to this problem is sending heartbeat messages to prevent an idle state and ensure your work operates consistently.

Application Error
Error or bugs in code can be another reason for the SocketException e.g. a situation where a person tries to send a message to a server after it has been turned off or disconnected from the network.

SocketException Example
First, have a look at what SocketException is and how it is generated. Let's take a simple code example that can generate a SocketException.

Import the necessary package for SocketException:

```
import java.net.SocketException;

```
In the above snippet, we have imported the SocketException class from the “net” package of Java. This is used to handle errors when working with network connections. It allows us to deal efficiently with the errors.
 
Following is the code snippet:

```
public class SocketExceptionExample {
  public static void main(String[] args) {
    try {
      throw new SocketException("Simulated SocketException");
    } catch (SocketException e) {
       e.printStackTrace();
      }
  }
}
```
The operation performed by the above-given code is:
-	Create a class named “SocketExceptionExample”.
-	Create a main method for the code.
-	Specify a try-catch block.
-	In the try block, throw the SocketException as “Simulated SocketException”.
-	In the catch block, use the SocketException object to fetch the error message and store it in a variable “e”.
-	Then, use the “printStackTrace()” method to print the error faced.

Output
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c41zuyffqs4ilnus1moc.png)

How to Handle SocketException in Java?
To handle SocketException in Java, let’s take an example of a client-server. For this purpose, first, create a server and connect it with a local host. Then, create a client on the same device that can generate requests on the started server and the exception can be handled to execute the code smoothly.

To handle the SocketException in Java, go through the listed steps.

Step 1. Create a SocketServer Class
Create a class named “SocketServer”  that enables the clients to connect and send messages which will be read by the outstream. 
To do so, import the following packages:

```
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.ServerSocket;
import java.net.Socket;
```

The function of each class imported from respective packages is
-	“import java.io.ObjectInputStream” imports the “ObjectInputStream” class which is used to read objects from the input stream.
-	“import java.io.ObjectOutputStream” imports the “ObjectOutputStream” class used to write objects on the output stream.
-	“import java.lang.ClassNotFoundException” imports the “ClassNotFoundException”’ class which will handle the situation when a user cannot find the required class.
-	“import java.net.ServerSocket” imports the “ServerSocket” class utilized to check for incoming network connections.
-	“import java.net.Socket” imports the “Socket” class which is used to establish a client-side connection with our server.

Code to create and start the "SocketServer" by utilizing the preceding packages:

```
public class SocketServer {
  private static ServerSocket server;
  private static int port = 9876;
  public static void main(String args[]) throws IOException,    ClassNotFoundException{
       server = new ServerSocket(port);
       while(true){
      System.out.println("Waiting for the client request");   
      Socket socket = server.accept();
      ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
      String message = (String) ois.readObject();
      System.out.println("Message Received: " + message);
      ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
      oos.writeObject("Hello "+message);
      input.close();
      output.close();
      socket.close();
      if(message.equalsIgnoreCase("exit")) break;
    }
  System.out.println("Shutting down Socket server!!");
    server.close();
  }
}
```

The functions performed by the above code are:
-	Declare a class named “SocketServer”.
-	“server = new ServerSocket(port)” declares a private static variable of the “ServerSocket” type for the server.
-	“private static int port = 9876” declares a static variable named “port” and specifies the port number. assign “9876” to it.
-	Then, define a main method that can throw the following exceptions “IOException” and “ClassNotFoundException”.
-	“server = new ServerSocket(port)” creates an object of ServerSocket and assigns it to ‘server’. It is responsible for checking incoming network connections.
-	Initiate a while loop set at the “true” condition.
-	“Socket socket = server.accept()” waits for the client to connect and grants access for connecting.
-	“ObjectInputStream input = new ObjectInputStream(socket.getInputStream())” creates an object named “input” that reads data from the input stream of the client.
-	“String message = (String) input.readObject()” reads the message from the client and changes the data type to string and stores it in the variable “message”.
-	“System.out.println("Message Received: " + message)” prints the received message.
-	“ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream())” creates an object used to write data to the client's output stream.
-	“output.writeObject("Hello " + message)” gives a response to the client's output stream.
-	“input.close()” closes the input stream.
-	“output.close()” closes the output stream.
-	“socket.close()” closes the socket connection with the client.
-	“if (message.equalsIgnoreCase("exit")) break” checks if the client sends an ‘exit’ message and terminates the server connection.
-	“server.close()” closes the server socket.


Step 2. Create a SocketClient Class
Create another class named “SocketClient” to generate requests on the created server. Send some messages to the created server for verification.

The required packages and classes to be imported are:

```
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
```

The function of each line is:
-	“import java.io.IOException” imports “IOException” class which handles errors related to input-output.
-	The classes from the “.net” package are used to deal with networking connections, working with IP addresses, and dealing with socket connections.

The code to generate the "SocketClient" is provided below:

```
public class SocketClient {
  public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException{
      InetAddress host = InetAddress.getLocalHost();
    Socket socket = null;
    ObjectOutputStream output = null;
    ObjectInputStream input = null;
    for(int i=0; i<5;i++){
        socket = new Socket(host.getHostName(), 9876);
        output = new ObjectOutputStream(socket.getOutputStream());
        System.out.println("Connection request to Socket Server");
        if(i==4)output.writeObject("exit");
        else output.writeObject(""+i);
        input = new ObjectInputStream(socket.getInputStream());
        String message = (String) input.readObject();
        System.out.println("Message: " + message);
        input.close();
        output.close();
        Thread.sleep(100);
    }
  }
}
```
The description for the above-provided code is mentioned below:
-	Declare a class “SocketClient”.
-	Declare a “main” method.
-	“InetAddress.getLocalHost()” is called to get our local machine’s IP address.
-	A variable “socket” is declared to hold a connection to the server.
-	“ObjectOutputStream” variable named “output” is used to write data to the server.
-	The variable called "input" of type "ObjectInputStream" is used to retrieve or get information from the server.
-	A loop is initiated to execute “5 times”.
-	A socket connection is built using the machine’s IP address and port number.
-	Data is sent to the started server via the "output" object.
-	A notification is displayed to indicate that someone wants to connect with you.
-	Based on the value of “i”, either the message “exit” is sent to the server or the value of ‘i’.
-	The received message is printed.
-	Close the input and output stream.
-	“Thread.sleep()” method is used to pause the program for 100 milliseconds.
 

Step 3. Running the SocketServer Class
First, run the “SocketServer” class to start the server.
The following output will appear:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nmjvoaw2bgnzixr9ibr3.png)


 
The above output indicates that the server has been started and is waiting for the client to connect.

Step 4. Running the SocketClient Class
Run the “SocketClient” class. It will allow the client to connect with the server started in the above step.
The below output shows that the client has successfully sent the connection request and messages to the server:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rrcl1h98as21kthj12ih.png)

Step 5. Server Output After Client Messages
The “SocketServer” class will also accompany some output which shows that the server had established a connection with the client and received all the messages before the termination of the connection:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s5hkv3upsi198bz1zrdg.png)

That’s all about handling SocketException in Java.

Conclusion
SocketException in Java is a checked exception that indicates a socket creation or access error. To handle a SocketException, it is important to identify the cause, implement specific solutions, use try-catch blocks, terminate resources appropriately, and consider implementing error logging to troubleshoot. The complete implemented tutorial has been given to handle the SocketException in Java.