×

Java.net.SocketException

Exception

The problem occurred during the execution of the program. If an exception occurs in the program, the program gets terminated. To skip the exception occurring statements, we have to handle the exception.

To handle the exception, we have four keywords:

  1. try
  2. catch
  3. throw
  4. throws
  5. finally

Exceptions are of two types.

  1. Checked Exception

    Ex: IOException, SQlException, ClassNotFoundException,FileNotFoundException, etc.
  2. Unchecked Exception

    Ex: ArithematicException, ArrayIndexOutOfBoundException, NullPointerException, ClassCaseException.

Java.net.SocketException

IOException is the parent class of the SocketException class.SocketException occurs when a problem is trying to open or access the socket. SocketException class inherits the properties of the IOEception class. All Exception classes are present in the Exception class, and this class is a subclass of the Object class.

As you would be aware, it's unequivocally encouraged to utilize the most unambiguous attachment exemption class that assigns the issue all the more precisely. It is additionally important that SocketException typically accompanies a blunder message that is extremely enlightening about the circumstance that caused the special case.

Socket Exception hierarchy:

Java.net.SocketException in Java

What is Socket Programming?

A programming idea utilizes attachments to lay out associations and empowers various projects to connect with one another utilizing an organization. Attachments give a point of interaction to lay out correspondence utilizing the organization convention stack and empower projects to share messages over the organization.

Attachments are endpoints in network correspondences. An attachment server is normally a multi-strung server that can acknowledge attachment association demands. An attachment client is a program/process that starts an attachment correspondence demand.

Java.net.SocketException in Java

java.net.SocketException: Connection reset

When the client shuts the attachment association in the client-side app the SocketException happens on the server-side before the reaction can be returned over the attachment. For instance, by stopping the program before the reaction was recovered. Association reset essentially implies that a TCP RST was gotten. TCP RST parcel is the remote side letting you know the association on which the past TCP bundle is sent isn't perceived, perhaps the association has shut, perhaps the port isn't open, and something like this. A reset parcel is basically one with no payload and with the RST bit set in the TCP header banners.

Presently as of execution, plainly, we want two projects, one dealing with the client and the other taking care of the server. They are as per the following:

Example 1: Server-side

// java program to implement SocketException in server-side App
// Importing required packages and class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class HelloWorld {
// Main driver method
public static void main(String[] args)
throws InterruptedException
{
new Thread(new Server()).start(); // calling the constructor and running the thread
}
static class Server implements Runnable {
// run() method for thread
@Override public void run()
{
ServerSocket s = null;
// To check exception we are using try block
try {
s = new ServerSocket(3333);
s.setSoTimeout(0);
// the loop iterates till the condition is true
while (true) {
try {
Socket client
= s.accept();
// Object creation to the BufferReader class
BufferedReader inputReader
= new BufferedReader(
new InputStreamReader(
client
.getInputStream()));
System.out.println(
"Client said :"
+ inputReader.readLine());
}
// Exception handling
catch (SocketTimeoutException e) {
e.printStackTrace();
}
}
}
// Exception handling using catch block
catch (IOException e1) {
e1.printStackTrace();
}
finally {
try {
if (s != null) {
s.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Example 2: Client side

// java program to implement SocketException in client-side App
// Importing required packages and class
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
public class HelloWorld{
public static void main(String[] args)
{


// anonymous inner class
// calling the constructor and running the thread
new Thread(new Client()).start();
}


static class Client implements Runnable {


@Override public void run()
{


// initializing  value to the Socket s
Socket s = null;


// checking Exception using try block
try {
s= new Socket("localhost", 3333);


// object creation to the PrintWriter class
PrintWriter outWriter = new PrintWriter(
s.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!");
}
// Handling the Exceptions using the catch block


// Catch block 1 for Exception handling
catch (SocketException e) {


// displaying the line where the Exception has occured
e.printStackTrace();
}


// Catch block 2for Exception handling
catch (InterruptedException e) {
e.printStackTrace();
}


// Catch block 3for Exception handling
catch (UnknownHostException e) {
e.printStackTrace();
}


// Catch block 4for Exception handling
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
// If the value of the socket is NULL then close the Socket
if (s != null)
// Close the socket
s.close();
}
                                          // catching the IOException
catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Output:

Java.net.SocketException in Java

Related Topics

How to Convert String to long in Java

How to Convert String to long in java It is used when you want to perform the mathematical operation on the String which contains long number then the conversion from String...

4 minutes read.

Java Print Writer

PrintWriter: It is used to write output data from the file. It is the class of Java.io package. It inherits the properties of the Writer class. Writer Class: It is a class of...

4 minutes read.

PriorityQueue in Java

PriorityQueue in Java A PriorityQueue is a member of the Java Collection Framework and is used when the values are needed to be processed based on priority. Priority queue operates similar to...

8 minutes read.

Equilibrium Index of an Array in Java

An array's equilibrium index is the condition where the sum of items with lower and higher indices equals. For example, an array A=[-4,5 2,6,-5] where: a[0]=-4, a[1]=5, a[2]=2, a[3]=6, a[4]=-5 Now according...

4 minutes read.

Java Math IEEEremainder() Method

The IEEEremainder() method of Math class calculates the remainder as prescribed by the IEEE754 standard. This method simply returns the remainder when f1 (dividend) is divided by f2 (divisor). Syntax: public static...

2 minutes read.

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

How to Convert boolean to String in Java

How to Convert boolean to String in Java There are two methods to convert boolean to String. Using valueOf(boolean) method Using toString(boolean) method For both the above methods, if the passes Boolean...

2 minutes read.

Java throw

Java throw Sometimes it is required in the code to throw an exception deliberately. In order to achieve the same, the Java throw keyword should be used. One can throw either...

3 minutes read.

Java file Writer

File Writer: It is used to write all the data from text files. It inherits the properties from the Output Stream class. It is meant for writing characters. It is meant...

4 minutes read.

Sort Elements by Frequency in Java

To sort the elements in Java by using frequency, we need an input array. We should create a function that sorts the elements in an array by using their frequencies...

3 minutes read.

Highest precedence in Java

In Java, the operator is the first thing that springs to mind when discussing precedence. The order in which the operators in an expression are evaluated is controlled by a...

3 minutes read.

Insertion Sort in Java

Insertion Sort in Java Insertion sort in Java is a simple sorting algorithm that works in the same way as we hold cards in hand. Insertion sort does the sorting element-by-element,...

3 minutes read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

Root exception in java

Java: The main feature of java which is not in C or object oriented programming language is platform independence. Not only the platform independence there are many other features in java...

3 minutes read.

Program to find the duplicate characters in a string

Problem statement You have given with a string and your task is to find out the repeated characters from the string and print them. If no character is repeated, then you...

2 minutes read.

Advantages of Generics in Java

Generic offers a variety of benefits. The programmer's life is made easier by using generic Java. In this section, we are going to discuss about Java's generic’s and its benefits. 1....

4 minutes read.

Checked vs Unchecked Exceptions in Java

In this tutorial, we will discuss Java's checked and unchecked Exceptions. Exception An exception is an undesirable event that disrupts the normal flow of the program. An exception is thrown at runtime. It...

4 minutes read.

Comparetoignorecase in Java

In Java, the function compareToIgnoreCase ( ) is part of the String class, which is part of the java.lang package. It is used to compare any two strings while disregarding...

4 minutes read.

Java String charAt() method

It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1. Syntax: public char charAt (int index) Parmeters It accepts only...

3 minutes read.

Java 13 New Features

The Java SE Platform's JDK 13 version is an open-source reference implementation defined by the Java Community's JSR 388 Process. The necessary modifications made in Java 13 are listed below....

6 minutes read.