对于tcp绑定服务器套接字,我们按如下方式读取它:
val BufSize = (Math.pow(2, 20) - 1).toInt // Far more than necessary
val is = new BufferedInputStream(socket.getInputStream)
val os = new BufferedOutputStream(socket.getOutputStream)
val buf = new Array[Byte](BufSize)
val nread = is.read(buf)
println(s"Nread=$nread")
我们看到nread
的值低于2K,即使对于长度达100K的缓冲区也是如此。当发送的实际数据是<大约2K然后传输成功:但是自然对于任何更大的我们都有EOF:
[WARNING]
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.readFully(ObjectInputStream.java:3063)
at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1914)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1529)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
at org.openchai.tcp.util.TcpCommon$.deserializeObject(TcpCommon.scala:43)
at org.openchai.tcp.util.TcpCommon$.deserializeStream(TcpCommon.scala:32)
at org.openchai.tcp.util.TcpCommon$.unpack(TcpCommon.scala:54)
at org.openchai.tcp.rpc.TcpServer$$anon$2.run(TcpServer.scala:112)
鉴于BufSize
是1兆字节为什么我们最终会遇到问题?
注意:如果将read
放入循环中,那么在第二次迭代时它就会挂起。这是尝试过的代码:
var nread = -1
var totalRead = 0
var off = 0
do {
if (!msgPrinted) {
debug("Listening for messages.."); msgPrinted = true
}
do {
println("about to read..")
nread = is.read(buf,off, buf.length-off)
totalRead += nread
println(s"read $nread bytes (totalRead=$totalRead)")
} while (nread > 0)
println(s"Final off=$off bytes=$totalRead")