服务器片段:
reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(connection.getInputStream())));
if (reader.ready()) {
result = reader.readLine();
if (result == null) {
quit(); // handle closing the socket
} else {
// process result
}
}
客户端片段:
BufferedOutputStream os = new BufferedOutputStream(connection.getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(os, "US-ASCII");
osw.write("hello\n");
osw.flush();
问题:
当客户端向服务器写入内容时,它会被正确读取,但是当客户端关闭它的套接字时(例如强制退出程序),reader.readLine()
应该输出null
,因为if (reader.ready()) {
null 结果永远不会到达quit()
。如果我离开if (reader.ready()) {
,服务器将无法读取数据。
我该如何解决?
编辑:我不能使用 awhile ((result = reader.readLine()) != null) {
因为我需要像这样运行更多代码:
while (running) {
try {
reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(connection.getInputStream())));
if (reader.ready()) {
result = reader.readLine();
if (result == null) quit();
else // process result
}
catch (Exception e) { ... }
// more code
}
}