有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    问题是你在读下一行,然后忽略它,然后又试图读下一行。第二次读取下一行时,没有数据,因为第一次读取已经消耗了数据:

    while(input.readLine()!=null){
        res += input.readLine()+"\n";
    }
    

    尝试以下方法:

    String line = null;
    while((line = input.readLine()) != null) {
        res += line + "\n";
    }
    

    正如@JB Nizet提到的,这取决于服务器实际向客户端发送换行符以终止消息。如documentation for ^{}中所述:

    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.