<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Muhammad Bin Sikandar</title>
    <description>The latest articles on DEV Community by Muhammad Bin Sikandar (@muhammad_80).</description>
    <link>https://dev.to/muhammad_80</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1134150%2Ff05909da-8421-4236-959c-463798fb7288.png</url>
      <title>DEV Community: Muhammad Bin Sikandar</title>
      <link>https://dev.to/muhammad_80</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/muhammad_80"/>
    <language>en</language>
    <item>
      <title>How to Handle the UnsatisfiedLinkError Runtime Error in Java</title>
      <dc:creator>Muhammad Bin Sikandar</dc:creator>
      <pubDate>Thu, 10 Aug 2023 06:20:15 +0000</pubDate>
      <link>https://dev.to/muhammad_80/how-to-handle-the-unsatisfiedlinkerror-runtime-error-in-java-3ane</link>
      <guid>https://dev.to/muhammad_80/how-to-handle-the-unsatisfiedlinkerror-runtime-error-in-java-3ane</guid>
      <description>&lt;p&gt;Java is a powerful and secure programming language, but it can be subject to runtime errors. One such error is “UnsatisfiedLinkError”, which can occur when a method or native library is not found or loaded at runtime. This error usually indicates a problem in linking native code with Java code and can be resolved by ensuring that the appropriate native libraries are available and configured correctly.&lt;/p&gt;

&lt;p&gt;In this article, we will explore what the “UnsatisfiedLinkError” runtime error is and discuss the ways to handle it in Java.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;“UnsatisfiedLinkError” Example in Java&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

The code written below gives this error:
public class UnsatisfiedLinkErrorExample {
  static {
    System.loadLibrary("nonExistentLibrary");
  }
  public static void main(String[] args) {
    System.out.println("Hello, World!");
  }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In this code above:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  The “.loadLibrary()” method is used to load “nonExistentLibrary” which does not exist.&lt;/li&gt;
&lt;li&gt;  In the main method, we have written some code that needed to be executed.&lt;/li&gt;
&lt;li&gt;  The code gives us an error and won’t execute further because the “UnsatisfiedLinkError” error would show up:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk0i854v2udj7p8fqnaq8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk0i854v2udj7p8fqnaq8.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This message indicates that the library is not found in the desired location or is a mismatch in Java version compatibility. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Handle the “UnsatisfiedLinkError” Runtime Error in Java&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This error is thrown when a Java program is unable to load a native library that does not exist. It has different extensions on different operating systems such as “.so” in Linux, “.dll” in Windows, and “.dylib” in MacOS.&lt;/p&gt;

&lt;p&gt;Whenever users encounter the “UnsatisfiedLinkError” error, it is necessary to check for the underlying errors and implement an appropriate solution.&lt;/p&gt;

&lt;p&gt;Some common approaches to handling this error are given below.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Check the Library Path&lt;/strong&gt;&lt;br&gt;
The error occurs when JVM cannot locate the native library in the search path. One needs to ensure the library is present in one of the directories specified in &lt;strong&gt;“java.library.path”&lt;/strong&gt;. While running the Java program, users can manually set up the path by the following below command:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

-Djava.library.path=&amp;lt;path_to_directory&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here &lt;strong&gt;“path_to_directory”&lt;/strong&gt; needs to be specified by you according to the requirement.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Verify Library Names and Locations&lt;/strong&gt;&lt;br&gt;
It must be ensured that the library is named properly and placed in the expected location. The library name in the Java code must match your specified one. Lastly, you need to ensure that the library is easily accessible by the user running the program and has all required permissions enabled.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Loading the Library Explicitly&lt;/strong&gt;&lt;br&gt;
One can load the library manually to have better control over it. Instead of relying on JVM to load the library automatically, you can use the following command line to load it manually:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

System.loadLibrary("libraryName")



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;It loads the library with your specified name and minimizes the errors. Users can have more control to load the library specifying the method and time for loading.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Use the Full Library Path&lt;/strong&gt;&lt;br&gt;
If the path user tries to access is not available in &lt;strong&gt;“java.library.path”&lt;/strong&gt;, the user can access it by using the complete path. Consider the below code line to load the library from the desired path.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

System.load("path_to_library")



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here “path_to_library” is the path you need to specify according to your requirement. It fetches the library from your defined path.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Handle Platform-specific Libraries&lt;/strong&gt;&lt;br&gt;
When working with platform-specific libraries, make sure to use the correct version of the library that is compatible with the target platform.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. Debug and Diagnose&lt;/strong&gt;&lt;br&gt;
If the above-mentioned methods are not helpful you can use debugging to get more information about the error. By debugging, you can get valuable insight into the library loading process and identify any issues.&lt;/p&gt;

&lt;p&gt;The above steps can be utilized to handle the error. A simple demonstration of the error being handled is given below with code examples.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example: Handling “UnsatisfiedLinkError”&lt;/strong&gt;&lt;br&gt;
This error can be handled by using a try-catch block and the remaining code would execute successfully.&lt;br&gt;
To handle the “UnsatisfiedLinkError” exception, go through the below specified simple code:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

public class HandleUnsatisfiedLinkError {
  static {
    try {
      System.loadLibrary("nonExistentLibrary");
    } catch (UnsatisfiedLinkError e) {
        System.out.println("Error loading native library: " + e.getMessage());
  }
}
  public static void main(String[] args) {
    System.out.println("Hello, World!");
  }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The operations performed by the above code are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  The try-catch block is used to handle the “UnsatisfiedLinkError” exception when the library is loading.&lt;/li&gt;
&lt;li&gt;  If the library is present it will load without causing errors. Otherwise, it will print the error message by &lt;strong&gt;“e.getMessage()”&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;  A main method is created with any piece of code to demonstrate that the remaining code functions smoothly.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6yl10vptxaabrz0sibfe.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6yl10vptxaabrz0sibfe.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
Note: Thoroughly test your code after taking appropriate steps to resolve the UnsatisfiedLinkError, so that your Java program runs without any runtime error.&lt;/p&gt;

&lt;p&gt;That's all to handle “UnsatisfiedLinkError” in Java.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
"UnsatisfiedLinkError" is a Java runtime error that occurs when a program fails to load a required library. To fix this error, you can check the library path, check library names and locations, load the library explicitly, and use the full library path. By following these steps, you can fix the “UnsatisfiedLinkError” error and keep your Java program running smoothly.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>What is the Java Signature sign() method with Example</title>
      <dc:creator>Muhammad Bin Sikandar</dc:creator>
      <pubDate>Sun, 06 Aug 2023 17:39:25 +0000</pubDate>
      <link>https://dev.to/muhammad_80/what-is-the-java-signature-sign-method-with-example-4kbo</link>
      <guid>https://dev.to/muhammad_80/what-is-the-java-signature-sign-method-with-example-4kbo</guid>
      <description>&lt;p&gt;Java is a well liked and versatile language being utilize by developers for making mobile desktop and web apps. Java offers a variety of unique features, one of which is the “sign()” method in the Signature class that can be imported from the “security” package. Using this method, developers can create digital signatures that ensure the security and reliability of their programs. &lt;/p&gt;

&lt;p&gt;In this article, we will focus on the Java Signature sign() method and how to implement it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Digital Signature?&lt;/strong&gt;&lt;br&gt;
Digital signatures are like special codes that ensure that our document data is safe and has not been subject to any change. In Java, A digital signature can be used to guarantee data accuracy. A unique signature is created for a data piece using encryption techniques. Digital signature creation and verification are made possible by the Java Signature class.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is the Java Signature “sign()” Method?&lt;/strong&gt;&lt;br&gt;
The “sign()” function of the Java “Signature” class is an essential component. It creates a digital signature for a specific record. It records the resulting bytes in the output buffer starting at offset. To do this, use the “initSign()” method for regenerating the signing signature.&lt;/p&gt;

&lt;p&gt;Syntax&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

int Sign(byte[] outbuffer, int offset, int len)


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Creating a Digital Signature in Java&lt;/strong&gt;&lt;br&gt;
To create a digital signature there are a series of steps which are to be implemented in the correct order.&lt;br&gt;
Follow the give  steps for creating a digital signature.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1. Creating a Signature Instance.&lt;/strong&gt;&lt;br&gt;
Create an instance of the “Signature” class named as “signature” that is using the “getInstance()” method along with the algorithm as mentioned below: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

Signature signature = Signature.getInstance("SHA256WithDSA");


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The above code block is using the “SHA-256” hash function along with the “DSA” algorithm for generating and verifying digital signatures.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2. Initializing the Signature Instance&lt;/strong&gt;&lt;br&gt;
After creating the “signature” object, initialize it for usage. The method used to initialize the signature in Java is the “init()” method.&lt;br&gt;
Here is the code for initialization:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

SecureRandom secureRandom = new SecureRandom();
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
KeyPair keyPair = keyPairGenerator.generateKeyPair();
signature.initSign(keyPair.getPrivate(), secureRandom);


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The operations performed by the above-given code are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  First, create an instance of the “SecureRandom” class by specifying the object “secureRandom”. It will be utilized to create secure random numbers.&lt;/li&gt;
&lt;li&gt;  Next, create an object for the “KeyPairGenerator” class that is responsible for generating encryption keys for digital signature algorithms as used in the above example which is “DSA”.&lt;/li&gt;
&lt;li&gt;  Now, make another object for “keyPair” that will store the keypair generated by the “KeyPairGenerator”.&lt;/li&gt;
&lt;li&gt;  “signature.initSign(keyPair.getPrivate(), secureRandom);“ initializes an object named “signature” for signing. It is linked with a private key from “keyPair” and a random number generator “secureRandom”. By doing this it becomes ready for signing.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 3. Creating a Digital Signature&lt;/strong&gt;&lt;br&gt;
Now, user can create the digital signature. To do so, call the “update()” method and finish with the call to the “sign()” method. Use the below-specified block to create a digital signature:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

byte[] data = "Your_ String".getBytes("UTF-8");
signature.update(data);
byte[] digitalSignature = signature.sign();


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In this code:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  UTF-8 encoding is used to convert the “Your_String” into a sequence of bytes. The result is recorded in the “data“ variable.&lt;/li&gt;
&lt;li&gt;  “signature.update(data)” updates the “signature” object with data from the above step. The signature object is responsible for creating a digital signature.&lt;/li&gt;
&lt;li&gt;  To store the above-generated data, the “signature.sign()” stores the data in an array of “byte[]” type.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 4 . Verification of Digital Signature&lt;/strong&gt;&lt;br&gt;
Verification of a digital signature created by someone else can be done for authentication. Now, initialize a “Signature” instance for verification. &lt;br&gt;
Here is the code:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

Signature signature2 = Signature.getInstance("SHA256WithDSA");
signature.initVerify(keyPair.getPublic());


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The operation performed by the above-given code is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  First, create an instance for the “Signature” class that will utilize the “getInstance” method that will be used to create or verify the digital signature.&lt;/li&gt;
&lt;li&gt;  “initVerify()” initializes the verification process using the public key from the “keyPair” object. The “getPublic()” method is used to obtain a public key.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now, use the public key of the public/private key pair to initialize into verification mode. After initialization, verification of the digital signature can be done by the “Signature” class. &lt;br&gt;
Following is the code snippet:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

byte[] data2 = "Your_String".getBytes("UTF-8");
signature2.update(data2);
boolean verified = signature2.verify(digitalSignature);


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The operation performed by the above-given code is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  “.getBytes("UTF-8")” method converts the string “Your_String” to a sequence of bytes using UTF-8 encoding.&lt;/li&gt;
&lt;li&gt;  “update(data2)” method updates the “signature2” object with bytes created in the above step.&lt;/li&gt;
&lt;li&gt;  “verify(digitalSignature)” is used to verify the signature and store the answer in the boolean format in the variable “verified”.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Complete Code&lt;/strong&gt;&lt;br&gt;
The complete code must be written in a class by importing the desired packages and classes.&lt;br&gt;
Import the following classes before writing the code:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

import java.security.*;
import java.util.Base64;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The function of these packages and their classes are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  “import java.security.*” imports all classes from the security package.&lt;/li&gt;
&lt;li&gt;  “import java.util.Base64” imports the “Base64” encoding class represents binary data by utilizing the printable characters.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Then, declare a class comprising the below code: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

public class DigitalSignature {
  public static void main(String[] args) {
    try {
      Signature signature = Signature.getInstance("SHA256WithDSA");
      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
      SecureRandom secureRandom = new SecureRandom();
      keyPairGenerator.initialize(1024, secureRandom);
      KeyPair keyPair = keyPairGenerator.generateKeyPair();
      signature.initSign(keyPair.getPrivate());
      byte[] data = "Your_String".getBytes("UTF-8");
      signature.update(data);
      byte[] digitalSignature = signature.sign();
      String encodedSignature =     Base64.getEncoder().encodeToString(digitalSignature);
      System.out.println("Digital Signature: " + encodedSignature);
      Signature signature2 = Signature.getInstance("SHA256WithDSA");
      signature2.initVerify(keyPair.getPublic());
      byte[] data2 = "Your_String".getBytes("UTF-8");
      signature2.update(data2);
      boolean verified = signature2.verify(digitalSignature);
      if (verified) {
        System.out.println("Digital Signature Verified!");
      } else {
        System.out.println("Digital Signature Verification Failed!");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
The digital signature will show up as shown below and the second line would indicate its verification:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbvc0unpg1rvir3dt1vou.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbvc0unpg1rvir3dt1vou.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
That’s all about the Java Signature “sign()” method.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
The “sign()” method is used to create unique digital signatures for data. It ensures data is authentic and original. It changes if the data is modified. Digital signatures play an important role in secure communication and data integrity. This post has described the complete functionality of the Signature “sign()” method along with proper implementation.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>How to Handle the Socket Exception in Java</title>
      <dc:creator>Muhammad Bin Sikandar</dc:creator>
      <pubDate>Sun, 06 Aug 2023 17:29:17 +0000</pubDate>
      <link>https://dev.to/muhammad_80/how-to-handle-the-socket-exception-in-java-53hk</link>
      <guid>https://dev.to/muhammad_80/how-to-handle-the-socket-exception-in-java-53hk</guid>
      <description>&lt;p&gt;Java is a powerful and secure programming language used by developers in web development, and app development. Being a programming language, it is subject to runtime exceptions. These exceptions can be handled to make the code run smoothly. SocketException is a subclass of IO Exception. As the name suggests, it is an exception thrown to show that an error has occurred while creating or accessing the socket. It is a type of exception that needs to be dealt with in a specific way called "throwing" or "handling" using a special code structure called a try-catch block.&lt;/p&gt;

&lt;p&gt;In this article, users will get an idea about SocketException in Java, its causes, and how to handle it.&lt;/p&gt;

&lt;p&gt;Common Reasons For SocketException&lt;br&gt;
The most frequent cause of SocketException in Java is reading or writing to or from a closed socket&lt;br&gt;
Another reason for this is the termination of the connection before the data has been read into the socket buffer. Several other reasons for SocketException are pointed out below:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Firewall Intervention&lt;/li&gt;
&lt;li&gt;  Slow Network &lt;/li&gt;
&lt;li&gt;  Long Idle Connection&lt;/li&gt;
&lt;li&gt;  Application Error&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Firewall Intervention&lt;br&gt;
Network Firewall can terminate the socket connections. If you have any firewall installed try turning it off and then check if the problem has been solved.&lt;/p&gt;

&lt;p&gt;Slow Network&lt;br&gt;
Slow Network can be the reason for the SocketException. To tackle the specified problem, extend the connection duration limit. This can greatly reduce the SocketException for slow connections using the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;socket.setSoTimeout(40000); // timeout set to 40,000 ms

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Long Idle Connection&lt;br&gt;
Another reason for the SocketException can be the long idle connection. It can be terminated from other ends to save resources. The solution to this problem is sending heartbeat messages to prevent an idle state and ensure your work operates consistently.&lt;/p&gt;

&lt;p&gt;Application Error&lt;br&gt;
Error or bugs in code can be another reason for the SocketException e.g. a situation where a person tries to send a message to a server after it has been turned off or disconnected from the network.&lt;/p&gt;

&lt;p&gt;SocketException Example&lt;br&gt;
First, have a look at what SocketException is and how it is generated. Let's take a simple code example that can generate a SocketException.&lt;/p&gt;

&lt;p&gt;Import the necessary package for SocketException:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.net.SocketException;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above snippet, we have imported the SocketException class from the “net” package of Java. This is used to handle errors when working with network connections. It allows us to deal efficiently with the errors.&lt;/p&gt;

&lt;p&gt;Following is the code snippet:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class SocketExceptionExample {
  public static void main(String[] args) {
    try {
      throw new SocketException("Simulated SocketException");
    } catch (SocketException e) {
       e.printStackTrace();
      }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The operation performed by the above-given code is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Create a class named “SocketExceptionExample”.&lt;/li&gt;
&lt;li&gt;  Create a main method for the code.&lt;/li&gt;
&lt;li&gt;  Specify a try-catch block.&lt;/li&gt;
&lt;li&gt;  In the try block, throw the SocketException as “Simulated SocketException”.&lt;/li&gt;
&lt;li&gt;  In the catch block, use the SocketException object to fetch the error message and store it in a variable “e”.&lt;/li&gt;
&lt;li&gt;  Then, use the “printStackTrace()” method to print the error faced.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Output&lt;br&gt;
&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc41zuyffqs4ilnus1moc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc41zuyffqs4ilnus1moc.png" alt="Image description" width="624" height="143"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;How to Handle SocketException in Java?&lt;br&gt;
To handle SocketException in Java, let’s take an example of a client-server. For this purpose, first, create a server and connect it with a local host. Then, create a client on the same device that can generate requests on the started server and the exception can be handled to execute the code smoothly.&lt;/p&gt;

&lt;p&gt;To handle the SocketException in Java, go through the listed steps.&lt;/p&gt;

&lt;p&gt;Step 1. Create a SocketServer Class&lt;br&gt;
Create a class named “SocketServer”  that enables the clients to connect and send messages which will be read by the outstream. &lt;br&gt;
To do so, import the following packages:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.ServerSocket;
import java.net.Socket;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The function of each class imported from respective packages is&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  “import java.io.ObjectInputStream” imports the “ObjectInputStream” class which is used to read objects from the input stream.&lt;/li&gt;
&lt;li&gt;  “import java.io.ObjectOutputStream” imports the “ObjectOutputStream” class used to write objects on the output stream.&lt;/li&gt;
&lt;li&gt;  “import java.lang.ClassNotFoundException” imports the “ClassNotFoundException”’ class which will handle the situation when a user cannot find the required class.&lt;/li&gt;
&lt;li&gt;  “import java.net.ServerSocket” imports the “ServerSocket” class utilized to check for incoming network connections.&lt;/li&gt;
&lt;li&gt;  “import java.net.Socket” imports the “Socket” class which is used to establish a client-side connection with our server.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Code to create and start the "SocketServer" by utilizing the preceding packages:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class SocketServer {
  private static ServerSocket server;
  private static int port = 9876;
  public static void main(String args[]) throws IOException,    ClassNotFoundException{
       server = new ServerSocket(port);
       while(true){
      System.out.println("Waiting for the client request");   
      Socket socket = server.accept();
      ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
      String message = (String) ois.readObject();
      System.out.println("Message Received: " + message);
      ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
      oos.writeObject("Hello "+message);
      input.close();
      output.close();
      socket.close();
      if(message.equalsIgnoreCase("exit")) break;
    }
  System.out.println("Shutting down Socket server!!");
    server.close();
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The functions performed by the above code are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Declare a class named “SocketServer”.&lt;/li&gt;
&lt;li&gt;  “server = new ServerSocket(port)” declares a private static variable of the “ServerSocket” type for the server.&lt;/li&gt;
&lt;li&gt;  “private static int port = 9876” declares a static variable named “port” and specifies the port number. assign “9876” to it.&lt;/li&gt;
&lt;li&gt;  Then, define a main method that can throw the following exceptions “IOException” and “ClassNotFoundException”.&lt;/li&gt;
&lt;li&gt;  “server = new ServerSocket(port)” creates an object of ServerSocket and assigns it to ‘server’. It is responsible for checking incoming network connections.&lt;/li&gt;
&lt;li&gt;  Initiate a while loop set at the “true” condition.&lt;/li&gt;
&lt;li&gt;  “Socket socket = server.accept()” waits for the client to connect and grants access for connecting.&lt;/li&gt;
&lt;li&gt;  “ObjectInputStream input = new ObjectInputStream(socket.getInputStream())” creates an object named “input” that reads data from the input stream of the client.&lt;/li&gt;
&lt;li&gt;  “String message = (String) input.readObject()” reads the message from the client and changes the data type to string and stores it in the variable “message”.&lt;/li&gt;
&lt;li&gt;  “System.out.println("Message Received: " + message)” prints the received message.&lt;/li&gt;
&lt;li&gt;  “ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream())” creates an object used to write data to the client's output stream.&lt;/li&gt;
&lt;li&gt;  “output.writeObject("Hello " + message)” gives a response to the client's output stream.&lt;/li&gt;
&lt;li&gt;  “input.close()” closes the input stream.&lt;/li&gt;
&lt;li&gt;  “output.close()” closes the output stream.&lt;/li&gt;
&lt;li&gt;  “socket.close()” closes the socket connection with the client.&lt;/li&gt;
&lt;li&gt;  “if (message.equalsIgnoreCase("exit")) break” checks if the client sends an ‘exit’ message and terminates the server connection.&lt;/li&gt;
&lt;li&gt;  “server.close()” closes the server socket.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Step 2. Create a SocketClient Class&lt;br&gt;
Create another class named “SocketClient” to generate requests on the created server. Send some messages to the created server for verification.&lt;/p&gt;

&lt;p&gt;The required packages and classes to be imported are:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The function of each line is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  “import java.io.IOException” imports “IOException” class which handles errors related to input-output.&lt;/li&gt;
&lt;li&gt;  The classes from the “.net” package are used to deal with networking connections, working with IP addresses, and dealing with socket connections.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The code to generate the "SocketClient" is provided below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class SocketClient {
  public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException{
      InetAddress host = InetAddress.getLocalHost();
    Socket socket = null;
    ObjectOutputStream output = null;
    ObjectInputStream input = null;
    for(int i=0; i&amp;lt;5;i++){
        socket = new Socket(host.getHostName(), 9876);
        output = new ObjectOutputStream(socket.getOutputStream());
        System.out.println("Connection request to Socket Server");
        if(i==4)output.writeObject("exit");
        else output.writeObject(""+i);
        input = new ObjectInputStream(socket.getInputStream());
        String message = (String) input.readObject();
        System.out.println("Message: " + message);
        input.close();
        output.close();
        Thread.sleep(100);
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The description for the above-provided code is mentioned below:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Declare a class “SocketClient”.&lt;/li&gt;
&lt;li&gt;  Declare a “main” method.&lt;/li&gt;
&lt;li&gt;  “InetAddress.getLocalHost()” is called to get our local machine’s IP address.&lt;/li&gt;
&lt;li&gt;  A variable “socket” is declared to hold a connection to the server.&lt;/li&gt;
&lt;li&gt;  “ObjectOutputStream” variable named “output” is used to write data to the server.&lt;/li&gt;
&lt;li&gt;  The variable called "input" of type "ObjectInputStream" is used to retrieve or get information from the server.&lt;/li&gt;
&lt;li&gt;  A loop is initiated to execute “5 times”.&lt;/li&gt;
&lt;li&gt;  A socket connection is built using the machine’s IP address and port number.&lt;/li&gt;
&lt;li&gt;  Data is sent to the started server via the "output" object.&lt;/li&gt;
&lt;li&gt;  A notification is displayed to indicate that someone wants to connect with you.&lt;/li&gt;
&lt;li&gt;  Based on the value of “i”, either the message “exit” is sent to the server or the value of ‘i’.&lt;/li&gt;
&lt;li&gt;  The received message is printed.&lt;/li&gt;
&lt;li&gt;  Close the input and output stream.&lt;/li&gt;
&lt;li&gt;  “Thread.sleep()” method is used to pause the program for 100 milliseconds.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Step 3. Running the SocketServer Class&lt;br&gt;
First, run the “SocketServer” class to start the server.&lt;br&gt;
The following output will appear:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnmjvoaw2bgnzixr9ibr3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnmjvoaw2bgnzixr9ibr3.png" alt="Image description" width="800" height="182"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The above output indicates that the server has been started and is waiting for the client to connect.&lt;/p&gt;

&lt;p&gt;Step 4. Running the SocketClient Class&lt;br&gt;
Run the “SocketClient” class. It will allow the client to connect with the server started in the above step.&lt;br&gt;
The below output shows that the client has successfully sent the connection request and messages to the server:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frrcl1h98as21kthj12ih.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frrcl1h98as21kthj12ih.png" alt="Image description" width="800" height="471"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Step 5. Server Output After Client Messages&lt;br&gt;
The “SocketServer” class will also accompany some output which shows that the server had established a connection with the client and received all the messages before the termination of the connection:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs5hkv3upsi198bz1zrdg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs5hkv3upsi198bz1zrdg.png" alt="Image description" width="800" height="480"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;That’s all about handling SocketException in Java.&lt;/p&gt;

&lt;p&gt;Conclusion&lt;br&gt;
SocketException in Java is a checked exception that indicates a socket creation or access error. To handle a SocketException, it is important to identify the cause, implement specific solutions, use try-catch blocks, terminate resources appropriately, and consider implementing error logging to troubleshoot. The complete implemented tutorial has been given to handle the SocketException in Java.&lt;/p&gt;

</description>
      <category>java</category>
      <category>development</category>
      <category>coding</category>
      <category>vscode</category>
    </item>
  </channel>
</rss>
