StreamCorruptedException接收到多个数据包
问题描述:
我有一个客户端服务器应用程序,其中我使用java serversocket(服务器端)和套接字(客户端)与java.nio选择器工具。我通过ObjectInput/Output Streams使用序列化对象在客户端和服务器之间交换消息。StreamCorruptedException接收到多个数据包
下面是用于从服务器这是相当标准的当服务器的时间很短的跨度内写入多个消息和所述客户端接收它们
enter code here
var msg:CommunicationMessage = null
var buf:ByteBuffer = ByteBuffer.allocate(1024);
var numBytesRead:Int = 0
try {
// Clear the buffer and read bytes from socket
buf.clear();
//println("Before Read")
numBytesRead = sChannel.read(buf)
//println("After Read " + numBytesRead)
numBytesRead match {
case -1 =>
println("Something Wrong with the Channel")
case 0 =>
//println("Nothing to read")
case _ =>
//println("Read some bytes")
// To read the bytes, flip the buffer
buf.flip();
// Read the bytes from the buffer ...;
// see Getting Bytes from a ByteBuffer
val bis:ByteArrayInputStream = new ByteArrayInputStream (buf.array());
val ois:ObjectInputStream = new ObjectInputStream (bis);
msg = ois.readObject().asInstanceOf[CommunicationMessage];
println("\n\n")
println("Received Message from Server")
msg.msgType match {
case CommunicationConstants.COMM_MSG_TYPE_RSP =>
println("updating server info")
updateServerInfo(msg.msgData)
case CommunicationConstants.COMM_MSG_TYPE_IND =>
if (serverAccepted) updateClientUI(msg)
}
}
} catch {
case e:StreamCorruptedException =>
println("Stream Corruption Exception received " + e.getCause())
case e:IOException =>
// Connection may have been closed
println("IO Exception received" + e.getCause())
}
enter code here
一切工作除了情况细接收消息的阶代码一起放入缓冲区并导致StreamCorruptedException。据我所知,objectinputstream不能在传入字节流中的多个序列化对象之间分隔,因此它会抛出这个无效的流错误。此外,即使我已经把捕捉它的例外,程序仍然挂起。
这可能是一个解决方案。 ?
1)根据长度字段在消息中创建我自己的分隔符以标识消息边界。
2)我也读过某个地方在每次接收后关闭套接字并开始一个新套接字。不知道这将如何帮助。
Plz建议。
在此先感谢
答
您需要发送分组ObjectOutputStream
超越了它的内容的长度。然后你知道有多少传入数据属于每个流,你可以相应地构建你的ByteArrayInputStream
。