gpt4 book ai didi

java - TCP 套接字无法接收数据包

转载 作者:行者123 更新时间:2023-11-30 00:38:40 25 4
gpt4 key购买 nike

我使用下面的代码从服务器接收消息,但它只收到一条消息,如“你好”,但第二条消息是“你好吗?”未被应用程序检测到。我试图修复它,但无法修复。

但是,没有任何错误。

这是我的代码:

new Thread(new Runnable() {
@Override
public void run() {
int available = 0;
while (true) {
try {
available = ClientInPutStream.available();
if (available > 0) {
break;
}
} catch (IOException e) {
msg = e.toString();
showMSG();
}
}
try {
char[] ServerMSG = new char[available];
Reader.read(ServerMSG, 0, available);
StringBuilder sb = new StringBuilder();
sb.append(ServerMSG, 0, available);
msg = sb.toString();
showMSG();
} catch (IOException e) {
msg = e.toString();
showMSG();
}
}
}).start();

提前致谢!

编辑:

我尝试了下面的代码,我发现需要通过更新 TextView 的按钮手动调用这个线程,您对此有什么解决方案吗? 为了使其自动化。

 new Thread(new Runnable() {
@Override
public void run() {
byte[] buffer = new byte[128]; // buffer store for the stream
int bytes; // bytes returned from read()
try {
bytes = ClientInPutStream.read(buffer);
byte[] readBuf = buffer;
String strIncom = new String(readBuf, 0, bytes);
msg2+=strIncom;
showmsg();
}catch (Exception e){msg=e.toString();showError();}
}

}).start();

最佳答案

它会做它被告知的事情。您的代码告诉您只接收一条消息。在 showMSG() 之后尝试 new Thread().start();。希望这会有所帮助。

解决方案

 new Thread(new Runnable() {

@Override
public void run() {

byte[] buffer = new byte[128]; // buffer store for the stream
int bytes; // bytes returned from read()

try {
while (true){ // continuously read buffer
bytes = ClientInPutStream.read(buffer);
byte[] readBuf = buffer;
String strIncom = new String(readBuf, 0, bytes); // create string from bytes array
msg2 += strIncom;
showmsg();
}
}catch (Exception e){msg=e.toString();showError();}
}

}).start();

关于java - TCP 套接字无法接收数据包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42938679/

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