gpt4 book ai didi

java - 聊天客户端传输时文本丢失

转载 作者:行者123 更新时间:2023-12-02 07:36:50 27 4
gpt4 key购买 nike

我有一个 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();
}
}

}

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

感谢您的帮助

最佳答案

每次调用 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

关于java - 聊天客户端传输时文本丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12104605/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com