java无法从输出流读取
我有一个服务器,可以向socket客户端发送字符串。当我试图从客户端获取字符串的内容时,它不会读取它。 服务器通过以下方式发送:
output.write(res); output.flush(); // I checked res content and it is all good
这是客户收到的:
public class Client {
public static void main(String[] args) throws IOException{
Socket connexion = new Socket(InetAddress.getLocalHost(), 33333);
BufferedReader input = new BufferedReader(
new InputStreamReader(connexion.getInputStream(), "8859_1"), 1024);
String res="";
while(input.readLine()!=null){
res += input.readLine()+"\n";
}
System.out.println(res);
}}
有什么建议吗?谢谢!
# 1 楼答案
问题是你在读下一行,然后忽略它,然后又试图读下一行。第二次读取下一行时,没有数据,因为第一次读取已经消耗了数据:
尝试以下方法:
正如@JB Nizet提到的,这取决于服务器实际向客户端发送换行符以终止消息。如documentation for ^{} 中所述: