我有一个客户端服务器应用程序,我在其中使用带有 java.nio 选择器工具的 java serversocket(服务器端)和套接字(客户端)。我通过 ObjectInput/Output Streams 使用序列化对象在客户端和服务器之间交换消息。
这是用于从服务器接收消息的 scala 代码,这是相当标准的
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)我还在某处阅读以在每次接收后关闭套接字并开始一个新的。不知道这将如何帮助。
请建议。
提前致谢