Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

java.net.SocketException – How to solve SocketException

In this example we are going to talk about java.net.SocketException. This is a subclass of IOException so it’s a checked exception. It is the most general exception that signals a problem when trying to open or access a socket.

As you might already know, it’s strongly advised to use the most “specific” socket exception class that designates the problem more accurately. It is also worth noting that SocketException, usually comes with an error message that is very informative about the situation that caused the exception.

1. A simple Client-Server Application

To demonstrate this exception, I’m going to borrow some code from the client-server application we’ve seen in java.net.ConnectException – How to solve Connect Exception. It consists of two threads. The first one, SimpleServer, opens a socket on the local machine on port 3333. Then it waits for a connection to come in. When it finally receives a connection, it creates an input stream out of it, and simply reads one line of text from the client that was connected. The second thread, SimpleClient, attempts to connect to the server socket that SimpleServer opened. When it does so, it sends a line of text and that’s it. This time though the two threads will be in different classes launched by two different main methods, so as to cause a SocketEception:

SimpleServerApp.java:

package com.javacodegeeks.core.socketecxeption;

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 SimpleServerApp {
	
	public static void main(String[] args) throws InterruptedException {

		new Thread(new SimpleServer()).start();

	}

	static class SimpleServer implements Runnable {

		@Override
		public void run() {

			ServerSocket serverSocket = null;

			try {
				serverSocket = new ServerSocket(3333);
				serverSocket.setSoTimeout(0);

				while (true) {
					try {
						Socket clientSocket = serverSocket.accept();

						BufferedReader inputReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

						System.out.println("Client said :"+ inputReader.readLine());

					} catch (SocketTimeoutException e) {
						e.printStackTrace();
					}
				}

			} catch (IOException e1) {
				e1.printStackTrace();
			} finally {
				try {
					if (serverSocket != null) {
						serverSocket.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

SimpleClientApp.java:

package com.javacodegeeks.core.socketecxeption;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;


public class SimpleClientApp {

	public static void main(String[] args) {
		
		new Thread(new SimpleClient()).start();

	}
	
	static class SimpleClient implements Runnable {

		@Override
		public void run() {

			Socket socket = null;
			try {

				socket = new Socket("localhost", 3333);
				
				PrintWriter outWriter = new PrintWriter(socket.getOutputStream(), true);
				
				System.out.println("Wait");

				Thread.sleep(15000);

				outWriter.println("Hello Mr. Server!");

			}catch (SocketException e) {
				e.printStackTrace();
			}catch (InterruptedException e) {
				e.printStackTrace();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {

				try {
					if (socket != null)
						socket.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}
		}
	}
}

As you can see, I’ve put a 15 second delay in SimpleClient for the client to wait before attempting to its message. It is important to notice that by the time the client calls sleep(), he has already created the connection to the server. What I’m going to do is start both threads and after the client makes the connection I will suddenly stop the client application.

Here’s what happens on the server side:

java.net.SocketException: Connection reset
	at java.net.SocketInputStream.read(SocketInputStream.java:196)
	at java.net.SocketInputStream.read(SocketInputStream.java:122)
	at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)
	at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
	at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
	at java.io.InputStreamReader.read(InputStreamReader.java:184)
	at java.io.BufferedReader.fill(BufferedReader.java:154)
	at java.io.BufferedReader.readLine(BufferedReader.java:317)
	at java.io.BufferedReader.readLine(BufferedReader.java:382)
	at com.javacodegeeks.core.lang.NumberFormatExceptionExample.SimpleServerApp$SimpleServer.run(SimpleServerApp.java:36)
	at java.lang.Thread.run(Thread.java:744)

As you can see we get a SocketException with the message Connection reset. This happens when on of the participants “violently” closes the connection without using close(). Of course you can provoke a “violent” close of the connection without having to close the application manually. In the client code, after waiting for 15 seconds (or less), you can throw a new exception (using throws new Exception()), but you have to remove the finally clause or else then the connection will close normally and no SocketException will be thrown.

2. How to solve SocketException

As we’ve already mentioned, SocketException is a general exception the designates a problem when trying to access or open a Socket. So as you can imagine, solving that problem has to be done with extra care. You shall always log the error message that accompanies the exception. In the previous example we’ve seen the message code>Connection reset. This happens when on of the participants "violently" closes the connection without using close(). This means that you should check whether one of the participants has terminated unexpectedly. One slightly bizarre message can be Too many open files, especially when you run on Linux. This message designates that to many file descriptors are open to the system. You can avoid that error if you go to /etc/sysctl.conf and raise the number in fs.file-max field. Additionally, you can try to give more stack memory.

Of course many other messages can be met. For example "Bind error", where your connection cannot be established because the port cannot be bind to the socket. In that case check if the port is already in use etc.

In the next few example we are going to look deeper into the subclass of SocketException to get a better understanding of it.

Download Source Code

This was an example on java.net.SocketException and how to solve SocketException. You can download the source code of this example here: SocketExceptionExample.zip

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close