BufferedReader 中的readLine方法读不到内容的原因

来源:互联网 发布:仿淘宝模板 编辑:程序博客网 时间:2024/05/01 01:21

BufferedReader 中的readLine方法读不到内容的原因


在偶尔的一次测试中,服务端和客户端通信时,客户端发送了如下内容:“come from clientcome from clientcome from clientcome from clientcome from clien”,然后我在服务端采用BufferedReader读取,代码如下

String str = "";
//readLine判断一行是以\r\n来判断的。如果最后一段字符没有\r\n,那么采用这种方式将无法读出剩下的字符串
while ((str=bfr.readLine()) != null) {
System.out.println("收到客户端发送过来的内容" + str);
}

结果发现根本就没有读出内容。

后来查看readLine方法得知,这个方法是以\r  \n  \r\n作为一行的判断标志的,这就可以解释为什么客户端明明发送了内容,服务端去没有读到的原因,不是没有发送过来,而是因为读取方式不对导致的。如果客户端想要让服务器能读出他发送的所有内容,那就必须在发送内容后面加上\r  \n  \r\n这些标志中的一个。

例如:"come from client\r\ncome from client\r\ncome from client\r\ncome from client\r\ncome from client\r\n"

这样在服务端能读到五个:come from client

如果发送:"come from client\r\ncome from client\r\ncome from client\r\ncome from client\r\ncome from client"

服务端只能读到四个:come from client

因为结束时没有添加\r\n

0 0