2

我正在使用 ByteBuffer 通过 java nio 传输数据。同一条消息可以发送给多个接收者。消息格式为“消息头+消息内容”。一种简单的方法是为每个接收器分配一个新的字节缓冲区。这不是有效的。

我的问题是 ByteBuffer 是否有类似的 java 函数指向 C/C++ 中的指针函数。所以我可以使用一个缓冲区来保存消息内容并与不同的标头连接。这样,就是效率。

谢谢。

4

2 回答 2

2

在 Java 中GatheringByteChannel,您可以使用 a (您很可能正在处理)。它允许拥有一个包含标头的静态缓冲区和一个用于每个客户端的单独缓冲区,其中包含不同的内容。对于一些入门材料,您可能需要查看此博客文章:

http://javaol.wordpress.com/2011/05/06/java-nio-scatter-gather/

于 2011-06-01T14:29:24.850 回答
0

我使用单个 ByteBuffer 发送到多个接收器。

ByteBuffer bb = ByteBuffer.allocateDirect(LARGE_BUFFER);
bb.clear();
bb.position(START_OF_CONTENT /* 1024 */);
appendContentTo(bb);
int endOfContent = bb.position();

bb.limit(endOfContent);
for(Connection conn: connections) {
    bb.position(START_OF_CONTENT);
    /* prepend header BEFORE the position and move the position back */
    conn.prependHeader(bb); 
    conn.write(bb);
}

这样,您可以为每个连接使用相同的 ByteBuffer。内容只有一份副本。

conn.prependHeader() 可能看起来像的示例

public void prependHeader(ByteBuffer bb) {
    // bb starts at the start of the content.
    int pos = bb.position();
    // it would be better if a byte[] wasn't required. This is just an example
    byte[] header = getHeaderAsBytes();
    bb.position(bb.position()-header.length);
    bb.put(header);
    // bb starts at the start of the header.
    bb.position(bb.position()-header.length);
}
于 2011-06-01T14:52:56.517 回答