V
V
Vitaly2014-05-19 14:42:26
Java
Vitaly, 2014-05-19 14:42:26

How to properly close a socket?

Client:
Open socket: Write data:
Socket socket = new Socket(host,port);

socket.getOutputStream().write("str");
socket.getOutputStream().flush();

Read data:
response = socket.getInputStream().read();
Close connection and socket:
socket.shutdownInput();
socket.shutdownOutput();
socket.close();


Server:
Socket clientSocket = serverSocket.accept();
message = clientSocket.getInputStream().read();
clientSocket.getOutputStream().write("str2");


In this case, clientSocket.isConnected() is true, and the server does not see that the client has disconnected. How can I track if a client has disconnected?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
ValdikSS, 2014-05-19
@silverhawk90

Can be read from inputstream. As soon as you get back a void (an empty string, ''), then this means that the client has disconnected (this is for blocking sockets).
On non-blocking sockets, you need to react to the signal.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question