×

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

Basic Terms in Multithreading

To understand the terms of multithreading, we must have knowledge about concurrency, processes, and threads. Concurrency The concurrency stands for performing multiple tasks at the same time. In the process communication, the operating system permits the process...

8 minutes read.

Java Location

PATH is an environmental variable that the system software now uses to find executable files (.exe) or Java binaries ( java or javac command). Once chosen, a route cannot be...

3 minutes read.

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.

How to run Java Program in Eclipse

How to run Java Program in Eclipse In this section, we will learn how to write, save, compile, and execute or run a Java program in Eclipse. Eclipse is one of...

2 minutes read.

Java Math.multiplyExact() method

In java, we are provided with multiplyExact method in the Math module. This Math module belongs to the java.lang package. In general, this method returns the product of the provided...

2 minutes read.

Program to find and replace characters on string in java

In JAVA, Strings are immutable. To overcome this Java String class contains a lot of methods to do operations on Strings. One such method is replace method. String Replace It returns a...

3 minutes read.

Java Boolean compare() method

The compare() method of Java Boolean class compares the specified Boolean values and returns a positive 1 or negative 1 or zero integer value based on the result. Syntax public static int...

2 minutes read.

Stack vs Heap in Java

In Java, whenever we declare an object or create a variable, whether it is an instance variable, local variable, or static variable, a certain memory is used to store the...

4 minutes read.

Java Polymorphism

The process of representing one form in multiple forms is known as Polymorphism. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means...

5 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Split the Number String into Primes in Java

Given is a string that only contains digits and serves to represent a number. Our goal is to split the string of numbers in a way that ensures each segment...

2 minutes read.

How to find characters with the maximum number of times in a string java

Problem statement In this problem, users want to find the maximum count of a character from the string and return the character along with its count. Your task is to create...

3 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.

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.

Java Volatile Keyword

The compiler, runtime, or processors may use any kind of optimization if there aren't any required synchronizations. Although most of the time these improvements are advantageous, they occasionally can result...

6 minutes read.

Java Enum

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four iterators named Club, Diamond,...

3 minutes read.

Jagged Array in Java

Prerequisite We must first understand what Arrays are and Multi-dimensional Arrays are before we can learn about Jagged arrays. Java Arrays: A collection of data types that are similar is called an...

5 minutes read.

Best Java Libraries

One of the most widely used programming languages is Java. Java has a large number of libraries, including the standard Java library that includes libraries such as java.lang, java.util, and...

7 minutes read.

Java Delete File

There are two techniques to erase a record in Java: Utilizing File.delete() technique.Utilizing File.deleteOnExit() technique. Using File.delete() technique: In Java, we can erase a document by utilizing the File.delete() technique for File class....

2 minutes read.

What’s new in Java 12

On March 19th, 2019, the Java 12th edition was released. After releasing this edition, they have decided to release every new edition every six months. This version is the advanced...

5 minutes read.