0

我有一个 Java 客户端/服务器聊天应用程序,在建立连接后,接收者只收到了大约四分之一的数据。问题可能是什么?这是确切发生的情况的打印屏幕: 应用程序的打印屏幕

从套接字读取的代码:

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 一次来检查它是否为空,然后保存下一行,然后打印下一行。因此(失败成功失败|失败成功失败等)的模式=仅显示消息2 + 5

于 2012-08-24T07:05:10.767 回答