我有多个客户端和一台服务器。服务器在一个线程中处理每个客户端。客户端必须向主服务器发送一个自定义对象。我检查了this和this,它们谈到了java.io.StreamCorruptedException: invalid type code: AC
我所遇到的错误。
但我不理解建议的解决方案。他继承了 ObjectOutputStream 并且在必须发送对象的第二次及以后的时间中不写入标头。这对我不起作用。
是否有另一种通过 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) {
}
}
}