【发布时间】:2013-12-11 22:05:06
【问题描述】:
TCP 网络消息可以分段。但是碎片消息很难解析,尤其是在传输超过一个字节的数据类型时。例如,如果 long 的某些字节我希望在第二个缓冲区中结束,buffer.getLong() 可能会失败。
如果可以即时重新组合多个 Channel,解析会容易得多。所以我想通过java.nio.channels.Pipe发送所有数据。
// count total length
int length = 0;
foreach (Buffer buffer: buffers) {
length += buffer.remaining()
}
// write to pipe
Pipe pipe = Pipe.open();
pipe.sink().write(buffers);
// read back from pipe
ByteBuffer complete = ByteBuffer.allocateDirect(length)
if (pipe.source().read(complete) != length) {
System.out.println("Fragmented!")
}
但这能保证完全填满缓冲区吗?或者管道会再次引入碎片吗?换句话说,条件的主体会达到吗?
【问题讨论】:
标签: java tcp buffer pipe bytebuffer