I'm having an issue trying to get a java server to realize an (android/java) client has closed a TCP socket connection. I figured when the client calls close()
on the socket
, the server would catch an IOException
, but this is not the case. t_recv
is a thread that receives from BufferedReader in
, and t_send
sends using a PrintWriter out
. Closing in
causes a timeout and crash, and closing out
doesn't really seem to do anything. The PrintWriter
is created in the contructor of the t_send
thread, and BufferedReader
is create in the contructor of the t_recv
thread. Trying to debug this, I created blank run()
methods in both threads, and the same behaviour occurs.
An interesting note: the client is an Android application, and whenever the emulator freezes and windows has to force close it, the IOException
is caught in the server and the "User xxxx left" message is displayed.
Client closing connection:
try {
// t_recv.in.close(); - times out and crashes
// t_send.out.close(); - appears to do nothing
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
Server waiting for client to disconnect:
for (;;)
{
try {
while ( (msg = in.readLine()) != null)
{
response = msg;
System.out.println(response);
server.broadcast(response);
}
} catch (IOException e) {
System.out.println("User '" + socket.getInetAddress().toString() + "' left");
try {
socket.close();
out.close();
in.close();
} catch (IOException e1) {
e1.printStackTrace();
System.exit(-1);
}
break;
}
}
Thanks for your time.
Assuming that in
is a BufferedReader, the error is in this line:
while ( (msg = in.readLine()) == null);
That will loop for ever if in
is currently at the EOF. It should be:
while ( (msg = in.readLine()) != null);
See javadoc for BufferedReader.readLine()
, paying specific attention to the conditions in which it returns null
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.