Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect a remote side socket close? [duplicate]

How do you detect if Socket#close() has been called on a socket on the remote side?

like image 475
Kevin Wong Avatar asked Sep 30 '08 02:09

Kevin Wong


People also ask

How do you know if a socket has been closed?

The most obvious way to accomplish this is having that process call read on the socket for a connection and check whether read returns 0 (i.e. reads zero bytes from the socket), in which case we know that the connection has been closed.

How can we detect that a TCP socket is closed by the remote peer in AC socket program?

You could check if the socket is still connected by trying to write to the file descriptor for each socket. Then if the return value of the write is -1 or if errno = EPIPE, you know that socket has been closed.

What can cause a socket to close?

Typically the things that cause a socket to close are: the client closes the socket. the server closes the socket, possibly due to a timeout. the server shuts down and issues a reset, either before shutdown or after restart, which closes the socket.

How do I identify a socket?

A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to. An endpoint is a combination of an IP address and a port number. Every TCP connection can be uniquely identified by its two endpoints.


1 Answers

The isConnected method won't help, it will return true even if the remote side has closed the socket. Try this:

public class MyServer {     public static final int PORT = 12345;     public static void main(String[] args) throws IOException, InterruptedException {         ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT);         Socket s = ss.accept();         Thread.sleep(5000);         ss.close();         s.close();     } }  public class MyClient {     public static void main(String[] args) throws IOException, InterruptedException {         Socket s = SocketFactory.getDefault().createSocket("localhost", MyServer.PORT);         System.out.println(" connected: " + s.isConnected());         Thread.sleep(10000);         System.out.println(" connected: " + s.isConnected());     } } 

Start the server, start the client. You'll see that it prints "connected: true" twice, even though the socket is closed the second time.

The only way to really find out is by reading (you'll get -1 as return value) or writing (an IOException (broken pipe) will be thrown) on the associated Input/OutputStreams.

like image 68
WMR Avatar answered Oct 14 '22 06:10

WMR