java - Socket isClosed() returns false after client disconnected -


this question has answer here:

in java application, have tcp server sends data generated in app connected clients. each new socket, create new thread. following thread code.

    public void run() {         try {             printstream printstream = new printstream(socket.getoutputstream(), true);             while (true) {                 if (socket.isclosed()) {                     break;                 }                 synchronized (datasource.getinstance()) {                     printstream.println(datasource.getinstance().getdata());                     try {                         datasource.getinstance().wait();                     } catch (interruptedexception e) {                         e.printstacktrace();                     }                 }             }         } catch (ioexception e) {             e.printstacktrace();         }     } 

data generating thread writes datasoure when new data available , calls notifyall() threads handles connected sockets wake , send available data clients.

my problem is, if client disconnected, socket.isclosed() returns true. thread handles socket never gets terminated.

why happen? how can exit thread when client gets disconnected?

there no "disconnect" tcp. peer can indicate not want send more (send fin) not mean not want receive anything. other end realizes read unwanted once tries , gets rst back.

if take "don't want read" indicator client closed (you might if application protocol way) can test if peer "disconnected" reading socket. system call returns no error 0 bytes , means there no more data peer. in java case gets translated eofexception.

apart socket not gets closed automatically, explicitly. isclosed returns true once socket got explicitly closed on local end. , isconnected not tell if other end "disconnected", tell if end did connect peer.

see java socket api: how tell if connection has been closed?.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -