gpt4 book ai didi

java - 重复写入 ObjectInputStream

转载 作者:行者123 更新时间:2023-12-01 15:16:20 24 4
gpt4 key购买 nike

我有多个客户端和一台服务器。服务器在一个线程中处理每个客户端。客户端必须向主服务器发送一个自定义对象。我检查了thisthis ,其中谈论错误 java.io.StreamCorruptedException: invalid type code: AC这正是我所拥有的。

但我不理解建议的解决方案。他继承了ObjectOutputStream并且简单地在第二次及之后必须发送对象的时候不写入 header 。这对我不起作用。

是否有另一种解决方案可以通过 TCP 套接字发送自定义对象?我的客户每 10 秒收集一次数据并重新创建发送的对象。

如果我重复了,我很抱歉,我正在阅读很多类似的问题,但没有找到适合我的情况的答案。

提前致谢

编辑

发送方法(在客户端)

    public void TCPEchoClientSend(MonitoredData _mData) throws IOException {
if (_mData == null)
throw new IllegalArgumentException("Parameter: <Monitored Data> empty.");
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

// Send the encoded object to the server
oos.writeObject(_mData);

oos.close();

System.out.println("Client sent the monitored data package.");

}

接收

public static void handleEchoClient(Socket client, Logger logger) {
try {
MonitoredData mdata;
// Get the input and output I/O streams from socket
ObjectInputStream ois = new ObjectInputStream(client
.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(client
.getOutputStream());

// Receive until client closes connection, indicated by -1;
while ((mdata = (MonitoredData) ois.readObject()) != null) {

System.out.println("Got received data. Ready to save.");

hdb.saveOrUpdate(mdata);

System.out.println("Monitored Data arrived at home.");

}

// logger.info("Client " + _clntSock.getRemoteSocketAddress()+
// ", echoed " + totalBytesEchoed + " bytes.");

} catch (IOException ex) {
logger.log(Level.WARNING, "Exception in echo protocol", ex);
} catch (ClassNotFoundException e) {
logger.log(Level.WARNING, "Exception in echo protocol", e);
} finally {
try {
client.close();
} catch (IOException e) {
}
}
}

最佳答案

在套接字的生命周期中,两端使用相同的ObjectOutputStreamObjectInputStream,并查找ObjectOutputStream reset()和writeUnshared() 方法。

参见this answer进行讨论。

关于java - 重复写入 ObjectInputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11549023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com