dod*_*onl 2 java io serialization
我正在构建客户端 - 服务器应用程序.现在我想使用以下代码将消息从客户端转发到所有其他客户端:
ArrayList<User> usrs = _usrHandler.getUsers();
for(User usr : usrs) {
if(!usr.getSocket().equals(_connection)) {
usr._oOut.writeObject(new CommunicationMessage(this._comMsg.getMessage(), CommunicationMessage.MSG,
this._comMsg.getUser()));
}
}
Run Code Online (Sandbox Code Playgroud)
在客户端,程序正在侦听消息.它抛出了这个异常:
java.io.StreamCorruptedException: invalid stream header: 7371007E
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:783)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:280)
at Connection$MessageListener.run(Connection.java:126)
at java.lang.Thread.run(Thread.java:637)
Run Code Online (Sandbox Code Playgroud)
消息监听:
while(this._loop) {
this._comMsg = (CommunicationMessage) this._dataInput.readObject();
SimpleAttributeSet attr = new SimpleAttributeSet();
attr.addAttribute(StyleConstants.CharacterConstants.Bold, Boolean.TRUE);
attr.addAttribute(StyleConstants.CharacterConstants.Foreground, _comMsg.getUser().getColor());
messageClient.addMessage(_comMsg.getUser().getNickName() + ": ", attr);
messageClient.addMessage(_comMsg.getMessage(), _comMsg.getUser().getColor());
_comMsg = null;
}
Run Code Online (Sandbox Code Playgroud)
有人看到错误吗?
你可能会让你的流变得曲折.
构造时ObjectInputStream,构造函数从流中读取前两个字节,期望它们是对象流中应存在的"魔术值".如果它们不存在,它会抛出StreamCorruptedException(这是ObjectInputStream源代码中的所有内容).
所以这样看来,你的包装InputStream在一个ObjectInputStream时候,其实从连接的另一端下来的数据是不实际的对象流.也许它仍在发送先前通信的数据.