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();
}
}
添加回答
举报