[英]Java/android socket.close() is not realized by server
I'm having an issue trying to get a java server to realize an (android/java) client has closed a TCP socket connection.我在尝试获取 java 服务器以实现(android/java)客户端已关闭 TCP 套接字连接时遇到问题。 I figured when the client calls
close()
on the socket
, the server would catch an IOException
, but this is not the case.我想当客户端在
socket
上调用close()
时,服务器会捕获一个IOException
,但事实并非如此。 t_recv
is a thread that receives from BufferedReader in
, and t_send
sends using a PrintWriter out
. t_recv
是从BufferedReader in
接收的线程,而t_send
使用PrintWriter out
发送。 Closing in
causes a timeout and crash, and closing out
doesn't really seem to do anything.关闭
in
导致out
和崩溃,而关闭似乎并没有真正做任何事情。 The PrintWriter
is created in the contructor of the t_send
thread, and BufferedReader
is create in the contructor of the t_recv
thread. PrintWriter
是在t_send
线程的构造函数中创建的,而BufferedReader
是在t_recv
线程的构造函数中创建的。 Trying to debug this, I created blank run()
methods in both threads, and the same behaviour occurs.尝试对此进行调试,我在两个线程中创建了空白
run()
方法,并且发生了相同的行为。
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.一个有趣的提示:客户端是一个 Android 应用程序,每当模拟器冻结并且 windows 必须强制关闭它时,
IOException
会在服务器中捕获并显示“用户 xxxx left”消息。
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:假设
in
是一个 BufferedReader,错误就在这一行:
while ( (msg = in.readLine()) == null);
That will loop for ever if in
is currently at the EOF.如果
in
当前位于 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
.请参阅
BufferedReader.readLine()
的 javadoc,特别注意它返回null
的条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.