1 回答

TA貢獻1847條經驗 獲得超11個贊
調用close()aDataOutputStream會關閉其關聯OutputStream的 ,關閉套接字OutputStream也會關閉套接字。這是記錄在案的行為。
但是,那應該沒問題,因為您的接收器代碼無論如何只希望接收 1 個字符串。每個 TCP 連接只調用dis.readUTF()一次。
如果要在單個連接中發送多個字符串,請不要dos.close()在發送端調用(至少在發送完所有字符串之前),并且dis.readUTF()在接收端循環調用直到接收到所有字符串。
dos = new DataOutputStream(s.getOutputStream());
for(int i = 0; i < logList.length; ++i){
String backupPayload = invertLogStringToJson(logList[i]);
dos.writeUTF(backupPayload);
}
dos.flush();
dos.close();
@Override
public void run() {
try {
while (true) {
mySocket = ss.accept();
dis = new DataInputStream(mySocket.getInputStream());
try {
while (true) {
message = dis.readUTF();
handler.post(() -> {
bufferIntentSendCode.putExtra("data", message);
ctx.sendBroadcast(bufferIntentSendCode);
});
}
} catch (IOException e) {
}
dis.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
或者,在發送實際字符串之前發送列表長度,然后在讀取字符串之前讀取長度:
dos = new DataOutputStream(s.getOutputStream());
// maybe other things first...
dos.writeInt(logList.length);
for(int i = 0; i < logList.length; ++i){
String backupPayload = invertLogStringToJson(logList[i]);
dos.writeUTF(backupPayload);
}
dos.flush();
// maybe other things next...
dos.close();
@Override
public void run() {
try {
while (true) {
mySocket = ss.accept();
dis = new DataInputStream(mySocket.getInputStream());
try {
// maybe other things first...
int length = dis.readInt();
for (int i = 0; i < length; ++i) {
message = dis.readUTF();
handler.post(() -> {
bufferIntentSendCode.putExtra("data", message);
ctx.sendBroadcast(bufferIntentSendCode);
});
}
// maybe other things next...
} catch (IOException e) {
}
dis.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
添加回答
舉報