请各位高手帮忙看看客户端关了readLine()为什么不报错.

wensshq 2014-08-28 11:14:07
import java.io.IOException;
import java.io.*;
import java.net.*;
public class ChatServer {

public static void main(String[] args) {

ServerSocket ss = null;
BufferedReader br = null;
Socket s = null;
boolean started = false;
try {
ss = new ServerSocket(8888);
} catch (BindException e) {
System.out.println("The port is already in use, please replace the port!");
System.out.println("The program has been in operation, please close and re run the program!");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}

try {
started = true;
while(started) {
boolean bConnected = false;
s = ss.accept();
bConnected = true;
System.out.println("a Client connected!");
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
while(bConnected) {
String str = br.readLine();
System.out.println(str);

}
System.out.println("a Client connected!");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(br != null) br.close();
if(s != null) s.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Client Closed!");
}
}
}

请帮忙看下代码中标红的地方.readLine()与readUTF()这个方法都是阻滞式的,为什么把客户端关了之后,就一直输出null, 而不是进入阻滞,或者是抛出异常.
...全文
161 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
skgary 2014-08-29
  • 打赏
  • 举报
回复
引用
readLine public String readLine() throws IOException 读取一个文本行。通过下列字符之一即可认为某行已终止:换行 ('\n')、回车 ('\r') 或回车后直接跟着换行。 返回: 包含该行内容的字符串,不包含任何行终止符,如果已到达流末尾,则返回 null 抛出: IOException - 如果发生 I/O 错误
返回null,说明已经结束了。

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧