[英]Java/android socket.close() is not realized by server
我在尝试获取 java 服务器以实现(android/java)客户端已关闭 TCP 套接字连接时遇到问题。 我想当客户端在socket
上调用close()
时,服务器会捕获一个IOException
,但事实并非如此。 t_recv
是从BufferedReader in
接收的线程,而t_send
使用PrintWriter out
发送。 关闭in
导致out
和崩溃,而关闭似乎并没有真正做任何事情。 PrintWriter
是在t_send
线程的构造函数中创建的,而BufferedReader
是在t_recv
线程的构造函数中创建的。 尝试对此进行调试,我在两个线程中创建了空白run()
方法,并且发生了相同的行为。
一个有趣的提示:客户端是一个 Android 应用程序,每当模拟器冻结并且 windows 必须强制关闭它时, IOException
会在服务器中捕获并显示“用户 xxxx left”消息。
客户端关闭连接:
try {
// t_recv.in.close(); - times out and crashes
// t_send.out.close(); - appears to do nothing
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
服务器等待客户端断开连接:
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;
}
}
谢谢你的时间。
假设in
是一个 BufferedReader,错误就在这一行:
while ( (msg = in.readLine()) == null);
如果in
当前位于 EOF,那将永远循环。 它应该是:
while ( (msg = in.readLine()) != null);
请参阅BufferedReader.readLine()
的 javadoc,特别注意它返回null
的条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.