×

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

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

4 minutes read.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

Java String endsWith() method

Checks whether this String ends with the specified suffix or not. Syntax public boolean endsWith(String Suffix) Parameter Suffix : It takes suffix as a parameter  i.e. Sequence of characters Returns It returns true when the current...

1 minute read.

Type Annotations in Java

Only declarations were eligible for annotations in earlier versions of Java. With Java 8, you may now annotate any type use, including types in declarations, generics, and casts: @Encrypted String data; List<@NonNull...

6 minutes read.

Java Try Resource

In Java, a try argument that specifies one or more resources is known as a try-with-resources statement. When your program is finished utilizing an object, it must be closed, which...

4 minutes read.

Pyramid Program in Java

Pyramid Program in Java In the previous section, we have discussed about the number pattern programs in Java. The logic for the number pattern and pyramid pattern is the same except...

2 minutes read.

Java Open File

Java Desktop class give an open() strategy to open a filr. It has a place with a java.awt package. Work area execution is stage subordinate, so it is important to...

5 minutes read.

Command Class in Java

We use the command class to run commands against the database. The Command class may find a set of parameter objects for use in sending values to a stored procedure...

3 minutes read.

Flag Pattern in Java

The flag pattern in Java can be printed, which will be covered in this part. Given how difficult they are to code, flag patterns are rarely asked by interviewers. We separate...

2 minutes read.

Java 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

Difference Between BufferedReader and FileReader

BufferedReader: To read data from a specified character stream, two classes are used: buffered readers and file readers. Both of them have advantages and disadvantages. Although how they operate is the...

6 minutes read.

Heart Pattern in Java

Heart Pattern is yet another intricate pattern program, however, due to its complexity, interviewers hardly ever inquire about it. Method for Printing the Heart Number Pattern Put the value of the total row...

2 minutes read.

Race Condition in Java

Java is a multi-threaded programming language, race conditions are more likely to arise. Mostly because data can change when multiple threads visit the same resource simultaneously. Race conditions are concurrency...

3 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

Equidigital in Java

In this section, we will understand what is an equidigital number and how to write Java programs to locate them. It is commonly asked in academic settings and Java coding...

4 minutes read.

What is String in Java?

What is String in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a Java...

4 minutes read.

How to Send SMS in Java with Example

Sending SMS messages in Java is a fairly common task, and there are a number of libraries and APIs available to help you do it. One popular option is to...

2 minutes read.

How to Solve the Deprecated Error in Java?

Deprecated Java methods should not be used because they are deprecated (often, there are better, more modern alternatives). API update. Until now, Java has kept everything backward compatible and never...

3 minutes read.

Java Integer reverse() method

The reverse() method of Java Integer class returns the value obtained by reversing the order of the bits in the 2’s complement binary representation. Syntax public static int reverse (int i)  Parameters The parameter...

1 minute read.

Diffie Hellman Algorithm in Java

In this section, you will be acknowledged about Diffie Hellman algorithm clearly step wise along with an example and also an example program. Diffie Hellman Algorithm One of the most significant algorithms...

3 minutes read.