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
OverlappingFileLockException in Java with Examples
An OverlappingFileLockException is thrown when attempting to acquire a lock that overlaps an existing or pending lock held by this process. This exception is thrown by the lock( ) and tryLock( ) methods of FileChannel if the requested lock region overlaps a file lock that is already held by some thr
5 min read
java.net.SocketOption Class in Java
The java.net.SocketOption is a socket option that is connected with a socket, as the set of channels packages is java.nio.channels.NetworkChannel that this interface has defined the setOption as well as the getOption methods to set and query's the channels within its Socket Options. --> java.net
5 min read
java.io.UnsupportedEncodingException in Java with Examples
The java.io.UnsupportedEncodingException occurs when an unsupported character encoding scheme is used in java strings or bytes. The java String getBytes method converts the requested string to bytes in the specified encoding format. If java does not support the encoding format, the method String get
3 min read
NotSerializableException in Java with Examples
Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly used in Hibernate, RMI, JPA, EJB, and JMS technologies. The reverse operation of serialization is called deserialization where byte-stream is converted into an object. The serialization and deseri
4 min read
java.net.SocketPermission Class in Java
The java.net.SocketPermisson class represents whether you have permission to access a network via sockets. A SocketPermission consists of a host and a set of actions. Class Declaration: public final class SocketPermission extends Permission implements SerializableConstructor: ConstructorDescriptionM
2 min read
java.net.Socket Class in Java
The java.net.Socket class allows us to create socket objects that help us in implementing all fundamental socket operations. We can perform various networking operations such as sending, reading data and closing connections. Each Socket object that has been created using with java.net.Socket class h
5 min read
java.net.BindException in Java with Examples
The java.net.BindException is an exception that is thrown when there is an error caused in binding when an application tries to bind a socket to a local address and port. Mostly, this may occur due to 2 reasons, either the port is already in use(due to another application) or the address requested j
2 min read
java.net.SocketImplFactory Class in Java
In Java, SocketImplFactory Class is an interface java.net.SocketImplFactory Class is defining a factory for SocketImpl instances, as this interface is usable by sockets classes to create the sockets execution that implements various policies through it. Interface java.net.SocketImplFactory Class is
2 min read
Field set() method in Java with Examples
The set() method of java.lang.reflect.Field is used to set the value of the field represented by this Field object on the specified object argument to the specified new value passed as parameter. The new value is automatically unwrapped if the underlying field has a primitive type. If the field is s
4 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction wi
5 min read