All Products
Search
Document Center

Mobile Testing:java_net_SocketException

Last Updated:Feb 28, 2022

Problem description

This exception occurs when the client fails to connect to the server for requesting the server to create a socket. This exception includes four categories: BindException, ConnectException, NoRouteToHostException, and PortUnreachableException. All of them can be caught by SocketException. The four categories are detailed in the following sections:

  1. BindException occurs when you fail to bind a socket to a local IP address and port pair.

  2. ConnectException occurs when a socket fails to connect to a remote IP address and port pair. A typical cause is that the remote host denies the connection request. For example, the remote host does not exist or the remote host does not listen on the port.

  3. NoRouteToHostException occurs when a socket fails to connect to a remote IP address and port pair. A common cause is that the socket is blocked by a firewall or a router that the socket must pass is interrupted.

  4. PortUnreachableException occurs when the ICMP Port Unreachable message is returned for packets over the connection.

Solution

This exception occurs when the client fails to connect to the server for requesting the server to create a socket. We recommend that you use the try catch finally block to catch the exception and handle it.

Example 1

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)

Problem description: This exception may occur on both the client and server. Two reasons can cause this exception. The first is that if the socket is closed at one end (this end closes the socket or this end is terminated due to an error) while the other end is still sending data. This exception occurs on the first packet sent (Connect reset by peer). The second is that one end is terminated but the connection is not closed. This exception occurs when the other end tries to read data from the connection (Connection reset). In other words, the exception is caused by read and write operations after the connection is terminated.

Solution: We recommend that you do not frequently send a large number of socket requests to increase pressure on the server and that you use the try catch block to catch the exception and handle it. For idempotent services, the client can retry a connection. If not, retry operations may cause repeated requests.

Sample code:

1. Server code

class SimpleServer implements Runnable {
    @Override
    public void run() {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(8111);
            serverSocket.setSoTimeout(3000);
            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 (SocketException e) {
            e.printStackTrace();
        }catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            try {
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2. Client code

class SimpleClient implements Runnable {
    @Override
    public void run() {
        Socket socket = null;
        try {
            socket = new Socket("localhost", 8111);
            PrintWriter outWriter = new PrintWriter(socket.getOutputStream(), true);
            System.out.println("Wait");
            Thread.sleep(15000);
            //throw new Exception("Random exception");
            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();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

Example 2

 java.net.ConnectException:Connection refused: connect
 at java.net.DualStackPlainSocketImpl.connect0(NativeMethod)
 at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
 at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
 at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
 at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
 at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
 at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
 at java.net.Socket.connect(Socket.java:579)
 at java.net.Socket.connect(Socket.java:528)
 at java.net.Socket.(Socket.java:425)
 at java.net.Socket.(Socket.java:208)

Problem description: This exception occurs when the server cannot respond to the connection request from the client. Cause: Invalid IP addresses or port numbers, server downtime, or firewalls.

Solution: This exception occurs when the server cannot respond to the connection request from the client. We recommend that you check whether the IP address or port is valid, whether the server is accessible, and whether a firewall is set. The sample code is the same as that in Example 1.

References