0

Java クライアント/サーバー チャット アプリケーションを使用していますが、接続が確立された後、データの約 4 分の 1 しか受信者が受信していません。問題は何でしょうか?正確に何が起こるかの印刷画面は次のとおりです。 アプリケーションの印刷画面

ソケットから読み取るコード:

public void somethingElse(){
    try {
           if(in.readLine() != null){
                messageBufferIn = in.readLine();
               System.out.println(in.readLine());
               chat.append(recipient + ": " + messageBufferIn + "\n");
           }
           } catch (IOException e) {
            e.printStackTrace();
          }     
}

上記のメソッドを実行するスレッドのコード:

public class chatListener extends Thread{
static main main = new main();
//static Thread mainThread = new Thread(main);
public void run(){
    while(main.isConnected == true){
        main.somethingElse();
    }
}

}

上記のスレッドは、接続が確立されるとすぐに実行されます

助けてくれてありがとう

4

1 に答える 1

2

in.readLine を呼び出すたびに、スキャナは次の行に移動します。基本的に使用したことのない行をスキップするため、何度か呼び出し続けることはできません。これを試して、somethingElse() を置き換えます。

public void somethingElse(){
    try {
           String line;//Added a variable to store the current line to; readLine is 
           //dynamic, it returns the next line each call, so if we store to a variable,
           //we only call it once, and hold that value
           if((line = in.readLine()) != null){// (line = in.readLine()) != null is shorthand to store readLine to line, and then check if that returned value is null or not
               System.out.println(line);//Print out the line
               chat.append(recipient + ": " + line + "\n");//Append it
           }
     } catch (IOException e) {
        e.printStackTrace();
     }     
}

以前は、in.readLine を 1 回呼び出して null かどうかを確認し、次の行を保存してから、次の行を出力していました。したがって、(失敗成功失敗|失敗成功失敗など)のパターン=メッセージ2 + 5のみが表示されます

于 2012-08-24T07:05:10.767 に答える