客户端与服务器之间通信收不到信息——readLine()
写服务器端和客户端之间通信,结果一直读取不到信息,在https://blog.csdn.net/yiluxiangqian7715/article/details/50173573
上找到了原因:使用BufferedReader的readLine()方法来读取信息,但是没有遇见行结束符“\n”,“\r”或“\r\n”还是会继续读取(即阻塞了),所以要想读取到信息,只需要在写入的时候加上行结束符。
BufferedReader的readLine方法源码如下:
/** * Reads a line of text. A line is considered to be terminated by any one * of a line feed ('\n'), a carriage return ('\r'), or a carriage return * followed immediately by a linefeed. * * @return A String containing the contents of the line, not including * any line-termination characters, or null if the end of the * stream has been reached * * @exception IOException If an I/O error occurs * * @see java.nio.file.Files#readAllLines */ public String readLine() throws IOException { return readLine(false); }
类似的还有RandomAccessFile的readLine():
/** * Reads the next line of text from this file. This method successively * reads bytes from the file, starting at the current file pointer, * until it reaches a line terminator or the end * of the file. Each byte is converted into a character by taking the * byte's value for the lower eight bits of the character and setting the * high eight bits of the character to zero. This method does not, * therefore, support the full Unicode character set. * * <p> A line of text is terminated by a carriage-return character * ({@code '\u005Cr'}), a newline character ({@code '\u005Cn'}), a * carriage-return character immediately followed by a newline character, * or the end of the file. Line-terminating characters are discarded and * are not included as part of the string returned. * * <p> This method blocks until a newline character is read, a carriage * return and the byte following it are read (to see if it is a newline), * the end of the file is reached, or an exception is thrown. * * @return the next line of text from this file, or null if end * of file is encountered before even one byte is read. * @exception IOException if an I/O error occurs. */ public final String readLine() throws IOException { StringBuffer input = new StringBuffer(); int c = -1; boolean eol = false; while (!eol) { switch (c = read()) { case -1: case '\n': eol = true; break; case '\r': eol = true; long cur = getFilePointer(); if ((read()) != '\n') { seek(cur); } break; default: input.append((char)c); break; } } if ((c == -1) && (input.length() == 0)) { return null; } return input.toString(); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术