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