我使用下面的代码接收来自服务器的消息,但它只获得一条消息,如“Hello”,但第二条消息是“你好吗?”应用程序未检测到。我试图解决它,但我无法解决。
但是,没有任何错误。
这是我的代码:
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();
提前致谢!
修改
我尝试了下面的代码,我需要通过一个更新文本视图的按钮手动调用 线程,你有什么解决方案吗? 以便自动化。
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();
答案 0 :(得分:1)
它做了它所告诉的事情。您的代码告诉您只接收一条消息。在showMSG()之后尝试new Thread().start();
。希望这会有所帮助。
答案 1 :(得分:0)
最终解决方案:
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){
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();