I am using ByteBuffer to transfer data with java nio. A same message can be sent to multiple receivers. The message format is "message header + message content". A staright way is to allocate a new byte buffer for each receiver. This is not effiecient.
My question is whether there is similar java function for ByteBuffer to pointer funciton in C/C++. So I can use one buffer to hol开发者_开发百科d message content and concate with different headers. In this way, it is efficiency.
thanks.
In Java your can use a GatheringByteChannel
(which you most probably are dealing with). It allows to have one static buffer containing the header and an individual buffer for each client holding the varying contents. For some material to get started you might want to check out this blog post:
http://javaol.wordpress.com/2011/05/06/java-nio-scatter-gather/
I use a single ByteBuffer to send to multiple receivers.
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);
}
This way, you can use the same ByteBuffer for every connection. There is only ever one copy of the content.
An example of what conn.prependHeader() might look like
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);
}
精彩评论