简体   繁体   English

从服务器读取多行

[英]Reading multiple lines from server

I'm open for other ways to do this, but this is my code:我对其他方法持开放态度,但这是我的代码:

public class Client {
    public static void main (String [] args) {
        try(Socket socket = new Socket("localhost", 7789)) {
            BufferedReader incoming = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter outgoing = new PrintWriter(socket.getOutputStream(),true);
            StringBuilder sb = new StringBuilder();

            Scanner scanner = new Scanner(System.in);
            String send = "";
            String response = "";

            while (!send.equals("logout")){
                System.out.println("Enter Command: ");
                send = scanner.nextLine();
                outgoing.println(send);
                while ((response = incoming.readLine()) != null) {
                    System.out.println(response);
                    sb.append(response);
                    sb.append('\n');

                    }
            }
        } catch (IOException e) {
            System.out.println("Client Error: "+ e.getMessage());
        }
    }
}

I do get response from the server, but the program is getting stuck in the inner while loop while ((response = incoming.readLine()) != null) , so i can't enter a second command.我确实得到了服务器的响应,但是程序卡在了内部 while 循环中while ((response = incoming.readLine()) != null) ,所以我无法输入第二个命令。 how do i break the loop if the incoming response is done ?如果传入的响应完成,我该如何打破循环?

The problem is that incoming.readLine() will only return null if the socket is closed, otherwise it will block and wait for more input from the server.问题在于,如果套接字关闭,则incoming.readLine()只会返回null ,否则它将阻塞并等待来自服务器的更多输入。

If you can change the server, you could add some marking that the request was fully processed and then check it like this while ((response = incoming.readLine()) != "--finished--") .如果您可以更改服务器,您可以添加一些标记,表明请求已被完全处理,然后像这样检查它while ((response = incoming.readLine()) != "--finished--")

If you cannot, try this:如果你不能,试试这个:

while(response.isEmpty()){
    if(incoming.ready()){ //check if there is stuff to read
        while ((response = incoming.readLine()) != null){
            System.out.println(response);
            sb.append(response);
            sb.append('\n');
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM