java.net.SocketException in Java with Examples
Last Updated :
12 Nov, 2021
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:
- First, check if the Server is running by doing telnet on the host port on which the server runs.
- Check if the server was restarted
- Check if the server failed over to a different host
- log the error
- 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.
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read