Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket does not throw exception when trying to write to closed connection

Tags:

java

sockets

i am new in java socket programming but i have faced the problem.
When i trying to write to connection that is unexpectedly closed in client side i don`t get any exception. I have Server side.

    public static void main(String[] args) throws IOException { 
    ServerSocket socket = new ServerSocket(8036);
    String st;
    while(true) {
        System.out.println("hello");
        Socket socket1 = socket.accept();
        BufferedReader reader = new BufferedReader(new InputStreamReader (socket1.getInputStream()));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket1.getOutputStream()));
        System.out.println(reader.readLine());
        writer.write("h");
        writer.flush();
    }
}

And Client

    public static void main(String[] args) throws  Exception{

    Inet4Address s = (Inet4Address)Inet4Address.getByName("localhost");
    System.out.println("begin");
     Socket socket = new Socket(s,8036);
     BufferedWriter w = new BufferedWriter (new OutputStreamWriter(socket.getOutputStream()));
     BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
     String h ;
     int prev = 0;
}

As you can see client exits immediately after connection, I even don't close socket, just try to model client that have exited unexpectedly. However I don't get exception in server side while trying write to socket. Why?

like image 321
Oleksandr Papchenko Avatar asked Jan 31 '14 17:01

Oleksandr Papchenko


1 Answers

  1. TCP cannot know on receiving a FIN that the peer has closed the connection for reading. It only knows that the peer has closed the connection for writing. It could have shutdown the connection for output and still be reading. So the first write to such a connection cannot be an error.

  2. When you write to a TCP connection, the data is buffered locally in the socket send buffer, and control is returned to the application. Writing to the network proceeds asynchronously. So the first write to a connection that has already been closed by the peer is unlikely to detect that. A subsequent write will.

NB your question is about writing to a connection that has been closed by the peer, not about writing to a closed socket. That would give you EBADF immediately.

like image 109
user207421 Avatar answered Oct 06 '22 07:10

user207421