[英]java - TCP Socket unable to receive packet
我使用下面的代碼從服務器接收消息,但它只收到一條消息,如“你好”,但第二條消息是“你好嗎?” 應用程序未檢測到。 我試圖修復它,但我無法修復。
但是,沒有任何錯誤。
這是我的代碼:
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();
它做它被告知的事情。 您的代碼告訴您只接收一條消息。 嘗試new Thread().start();
在showMSG()
。 希望這可以幫助。
解決方案
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.