[英]java - TCP Socket unable to receive packet
I used code below for receiving messages from a server but it only gets one message like "Hello," but the second message which is "How are you?"我使用下面的代码从服务器接收消息,但它只收到一条消息,如“你好”,但第二条消息是“你好吗?” is not detected by the application.
应用程序未检测到。 I tried to fix it but I was not able to.
我试图修复它,但我无法修复。
However, there is not any error.但是,没有任何错误。
Here is my code:这是我的代码:
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();
Thanks in advance!提前致谢!
EDIT:编辑:
I tried code below and I got that need to invoke this thread manually by a button which update text view do you have any solution for this?我尝试了下面的代码,但我需要通过更新文本视图的按钮手动调用此线程,您对此有什么解决方案吗? in order to automate it.
以使其自动化。
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();
It does what it is told to.它做它被告知的事情。 Your code tells to receive only one message.
您的代码告诉您只接收一条消息。 try
new Thread().start();
尝试
new Thread().start();
after showMSG()
.在
showMSG()
。 Hope this helps.希望这可以帮助。
solution解决方案
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.