文本在聊天客户端中传输时丢失

时间:2012-08-24 07:03:01

标签: java sockets

我有一个Java客户端/服务器聊天应用程序,在建立连接后,收件人只收到大约四分之一的数据。问题是什么?这是一个完全发生的打印屏幕: Printscreen of Application

从套接字读取的代码:

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

}

一旦建立连接,上面的线程就会运行

感谢您的帮助

1 个答案:

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