Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No exception is thrown when socket is closed

Tags:

java

sockets

When the server socket is closed the client doesn't receive any exception even after writing on the OutputStream and the server socket is already close.

Giving the following classes to test that:

public class ModemServerSocket {

    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocket serverSocket = new ServerSocket(63333);
        Socket client = serverSocket.accept();
        BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
        String s;

        while ((s = reader.readLine()) != null) {
            System.out.println(s);
            if (s.equals("q")) {                
                break;
            }
        }

        serverSocket.close();
    }

}

public class ModemClientSocket {

    public static void main(String[] args) throws IOException, InterruptedException {
        Socket socket = new Socket("localhost", 63333);
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"), true);
        String[] sArray = {"hello", "q", "still there?"};
        for (String s : sArray) {
            writer.println(s);
            if (s.equals("q")) {
                Thread.sleep(5 * 1000);
            }
        }
        System.out.println("Whoop. No exception. The client didn't notice.");       
    }

}

What I did was to launch the ModemServerSocket application then after that I launched the ModemClientSocket application.

ModemServerSocket Output:

hello 
q

ModemClientSocket Output:

Whoop. No exception. The client didn't notice.

Is this the expected behavior? Why is happening this?

However I did another test where I close the ModemClientSocket and the ModemServerSocket tries to read from the InputStream in that case I got an java.net.SocketException which is what I expected. The weird thing is that is not happening for the PrintWriter (OutputStream) and no exception is thrown.

I used Java 1.6.0 Update 26 for the tests.

like image 327
Alfredo Osorio Avatar asked Feb 22 '26 23:02

Alfredo Osorio


2 Answers

Quoting the JDK documentation of PrintWriter below.

Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError().

PrinterWriter Documentation

like image 96
DeFiNite Avatar answered Feb 25 '26 11:02

DeFiNite


I believe that closing the ServerSocket just means that no new connections will be accepted -- it doesn't close connections that have already been set up (You'd need to call client.close() in ModemServerSocket to do that).

like image 33
kylewm Avatar answered Feb 25 '26 13:02

kylewm