サーバーから複数の行を読みます

zojo:

私はこれを行うには他の方法のために開いているが、これは私のコードです:

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());
        }
    }
}

私は、サーバーからの応答を得るかが、プログラムは、内側のwhileループで立ち往生されてwhile ((response = incoming.readLine()) != null)、私は2番目のコマンドを入力することはできませんので、。入ってくる応答が行われた場合にどのように私は、ループを破るのですか?

Mireaラドゥ:

問題は、それがあるincoming.readLine()だけ返しますnullそれ以外の場合はブロックし、サーバーから複数の入力を待ちます、ソケットが閉じている場合。

サーバーを変更することができれば、あなたはいくつかの要求が完全に処理されたことをマーキングを追加し、このようにそれをチェックすることができますwhile ((response = incoming.readLine()) != "--finished--")

あなたは、これを試すことができない場合:

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');
        }
    }
}

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=371082&siteId=1
おすすめ