×

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

Java Thread Creation

Java provides the two ways to create a Thread: Implementing the Runnable interface.Extending the Thread class. Implementing Runnable interface The easiest way of creating a thread is to make a class that implements...

5 minutes read.

How to add double quotes in a string in Java

Strings are indicated using double-quotes. Double quotes are not printed; the values inside the double quotes are printed. There are different methods for adding double quotes to the string, such...

2 minutes read.

Java Math toRadians() Method

The toRadians() method of Java Math class converts an angle measured in degrees to an approximately equivalent angle measured in radian. Syntax: public static double toRadians (double angdeg) Parameters The parameter ‘angdeg’ represents an...

2 minutes read.

Calculator Program in Java

Calculator Program in Java A calculator performs the basic mathematical operations such as addition, subtraction, multiplication, etc. In this section, we will create a calculator program in Java using switch case...

5 minutes read.

How to Set Java_home in Linux

To set the Java_home in Linux, we must follow several steps to make us understand it easily.  Java follows the principle called WORA (write once run anywhere). We know that java...

3 minutes read.

Java Integer floatValue() method

The floatValue() method of Integer class returns a float value for this Integer after a widening primitive conversion. Syntax public float floatValue() Parameters NA Specified by This method is specified by floatValue in class Number Return Value This...

1 minute read.

Java String compareTo() Method

compareTo() method is used to compare the two specified Strings based on the alphabetical order(lexicographical order) of their characters.It returns positive number ,negative number or 0 Syntax: public int compareTo(String anotherString) Parameters: anotherString: the...

2 minutes read.

Vectors in Java

Vector Class We may make resizable arrays comparable to the ArrayList class using the Vector class, which implements the List interface. A vector is similar to a dynamic collection that can...

4 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.

Java Integer rotateLeft() method

The rotateLeft() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value left by the specified number of bits. Syntax public...

1 minute read.

Nonagonal number in Java

Figureate numbers with the form n(7n-5)/2 are known as nonagonal numbers. 7n+3 will be a triangular number if n is a nonagonal number. The nonagon is included in the idea...

4 minutes read.

Java program to count the occurrences of each character

The count of each character is the frequency of the characters. For example, the given String is “Programming”. In the given string, the count of the characters ‘P’ -1, ’r’-2,...

6 minutes read.

Java For Loop

A for loop is used to execute a set of statements for a fixed number of times. It takes the following form: for (initialization; condition; update) { statements; } The for loop defines...

2 minutes read.

Java Boyer Moore

A string searching or matching technique called the Boyer-Moore algorithm was created in 1977 by Robert S. Boyer and J. Strother Moore. It is the most popular and effective string-matching...

9 minutes read.

Java HashMap

Java HashMap extends AbstractMap and implements Map interface. It is the collection of multiple entries where an entry consists of key and value pair. The HashMap can contain only one...

7 minutes read.

Swing Program in Java

Java Swing is part of Java Foundation Classes (JFC). The swing toolkit is used to generate Graphical User Interface (GUI) for programs written in Java. The Java swing API is...

4 minutes read.

TreeSet in Java

Java TreeSet with Example Java TreeSet implements the Navigable Set interface. It stores the objects in ascending order. It contains unique elements. Access and retrieval time is fast. It does not...

8 minutes read.

Java LinkedList

LinkedList Java The Java LinkedList is used to store the elements by using a doubly linked list. It contains the duplicate items, also maintains the order of the insertion, the class...

5 minutes read.

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration. It can also be defined in another way, a...

4 minutes read.

Java Read File Line by line

Java provides two options to read files line by line. Each option offers different benefits and has its own set of drawbacks. Following are the ways through which on accomplish...

5 minutes read.