本文整理了Java中org.littleshoot.mina.common.ByteBuffer
类的一些代码示例,展示了ByteBuffer
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ByteBuffer
类的具体详情如下:
包路径:org.littleshoot.mina.common.ByteBuffer
类名称:ByteBuffer
[英]A byte buffer used by MINA applications.
This is a replacement for java.nio.ByteBuffer. Please refer to java.nio.ByteBuffer and java.nio.Buffer documentation for usage. MINA does not use NIO java.nio.ByteBuffer directly for two reasons:
fill
, get/putString
, and get/putAsciiInt()
enough.Allocation
You can get a heap buffer from buffer pool:
ByteBuffer buf = ByteBuffer.allocate(1024, false);
you can also get a direct buffer from buffer pool:
ByteBuffer buf = ByteBuffer.allocate(1024, true);
or you can let MINA choose:
ByteBuffer buf = ByteBuffer.allocate(1024);
Acquire/Release
Please note that you never need to release the allocated buffer because MINA will release it automatically when:
You have to release buffers manually by calling #release() when:
Wrapping existing NIO buffers and arrays
This class provides a few wrap(...) methods that wraps any NIO buffers and byte arrays. Wrapped MINA buffers are not returned to the buffer pool by default to prevent unexpected memory leakage by default. In case you want to make it pooled, you can call #setPooled(boolean)with true flag to enable pooling.
AutoExpand
Writing variable-length data using NIO ByteBuffers is not really easy, and it is because its size is fixed. MINA ByteBuffer introduces autoExpand property. If autoExpand property is true, you never get BufferOverflowException or IndexOutOfBoundsException (except when index is negative). It automatically expands its capacity and limit value. For example:
String greeting = messageBundle.getMessage( "hello" );
ByteBuffer buf = ByteBuffer.allocate( 16 );
// Turn on autoExpand (it is off by default)
buf.setAutoExpand( true );
buf.putString( greeting, utf8encoder );
NIO ByteBuffer is reallocated by MINA ByteBuffer behind the scene if the encoded data is larger than 16 bytes. Its capacity and its limit will increase to the last position the string is written.
Derived Buffers
Derived buffers are the buffers which were created by #duplicate(), #slice(), or #asReadOnlyBuffer(). They are useful especially when you broadcast the same messages to multiple IoSessions. Please note that the derived buffers are neither pooled nor auto-expandable. Trying to expand a derived buffer will raise IllegalStateException.
Changing Buffer Allocation and Management Policy
MINA provides a ByteBufferAllocator interface to let you override the default buffer management behavior. There are two allocators provided out-of-the-box:
fill
、get/putString
和get/putAsciiInt()
。ByteBuffer buf = ByteBuffer.allocate(1024, false);
您也可以从缓冲池获得直接缓冲:<
ByteBuffer buf = ByteBuffer.allocate(1024, true);
或者您可以让MINA选择:<<
ByteBuffer buf = ByteBuffer.allocate(1024);
获取/发布
请注意,您永远不需要释放分配的缓冲区,因为MINA将在以下情况下自动释放它:
*通过调用IoSession#write(Object)来传递缓冲区。
*通过调用IoFilter传递缓冲区。NextFilter#filterWrite(IoSession,IoFilter.WriterRequest)。
*通过调用ProtocolEncoderOutput#write(ByteBuffer)传递缓冲区。
而且,您不需要释放任何作为IoHandler#messageReceived(IoSession,Object)方法参数传递的ByteBuffer。当方法返回时,它们会自动释放。
在以下情况下,必须通过调用#release()手动释放缓冲区:
*您分配了一个缓冲区,但没有将缓冲区传递给上述两种方法中的任何一种。
*您调用了#acquire()以防止释放缓冲区。
包装现有NIO缓冲区和阵列
此类提供了一些换行(…)方法包装任何NIO缓冲区和字节数组。默认情况下,包装的MINA缓冲区不会返回到缓冲池,以防止意外的内存泄漏。如果要使其成为池,可以使用true标志调用#setPooled(布尔值)以启用池。
自动扩展
使用NIO ByteBuffers编写可变长度数据并不容易,因为它的大小是固定的。MINA ByteBuffer引入了自动扩展属性。若autoExpand属性为true,则永远不会获得BufferOverflowException或IndexOutOfBoundsException(索引为负时除外)。它会自动扩展其容量和限制值。例如:
String greeting = messageBundle.getMessage( "hello" );
ByteBuffer buf = ByteBuffer.allocate( 16 );
// Turn on autoExpand (it is off by default)
buf.setAutoExpand( true );
buf.putString( greeting, utf8encoder );
如果编码数据大于16字节,则NIO ByteBuffer将由MINA ByteBuffer在幕后重新分配。其容量和限制将增加到写入字符串的最后位置。
派生缓冲区
派生缓冲区是由#duplicate()、#slice()或#asReadOnlyBuffer()创建的缓冲区。它们非常有用,尤其是当您向多个会话广播相同的消息时。请注意,派生缓冲区既不是池也不是自动扩展的。尝试扩展派生缓冲区将引发IllegalStateException。
更改缓冲区分配和管理策略
MINA提供了一个ByteBufferAllocator接口,允许您覆盖默认的缓冲区管理行为。有两个现成的分配器:
*PooledByteBufferAllocator(默认)
*SimpleByteBufferAllocator
您可以通过调用#setAllocator(ByteBufferAllocator)来更改分配器。
代码示例来源:origin: org.littleshoot/xmpp
@Override
public ByteBuffer getBody() {
return ByteBuffer.wrap(body);
}
};
代码示例来源:origin: org.littleshoot/mina-port
@Override
public void write(int b) throws IOException {
ByteBuffer buf = ByteBuffer.allocate(1);
buf.put((byte) b);
buf.flip();
write(buf);
}
代码示例来源:origin: org.littleshoot/mina-port
@Override
public boolean equals(Object o) {
if (!(o instanceof ByteBuffer)) {
return false;
}
ByteBuffer that = (ByteBuffer) o;
if (this.remaining() != that.remaining()) {
return false;
}
int p = this.position();
for (int i = this.limit() - 1, j = that.limit() - 1; i >= p; i--, j--) {
byte v1 = this.get(i);
byte v2 = that.get(j);
if (v1 != v2) {
return false;
}
}
return true;
}
代码示例来源:origin: org.littleshoot/mina-port
@Override
public int hashCode() {
int h = 1;
int p = position();
for (int i = limit() - 1; i >= p; i--) {
h = 31 * h + get(i);
}
return h;
}
代码示例来源:origin: org.littleshoot/mina-port
public IoSessionInputStream() {
buf = ByteBuffer.allocate(16);
buf.setAutoExpand(true);
buf.limit(0);
}
代码示例来源:origin: org.littleshoot/mina-port
/**
* @see java.nio.Buffer#remaining()
*/
public int remaining() {
return limit() - position();
}
代码示例来源:origin: org.littleshoot/sip-stack
int oldPos = in.position();
int oldLimit = in.limit();
int count = matchCount;
while (in.hasRemaining())
byte b = in.get();
if (m_delimiterBuf.get(matchCount) == b)
if (matchCount == m_delimiterBuf.limit())
int pos = in.position();
in.limit(pos);
in.position(oldPos);
buf.put(in);
if (buf.position() > maxLineLength)
+ buf.position());
buf.flip();
buf.limit(buf.limit() - matchCount);
final String headers = buf.getString(decoder);
final Map<String, SipHeader> headersMap =
createHeadersMap(headers);
buf.clear();
in.limit(oldLimit);
代码示例来源:origin: org.littleshoot/mina-port
ByteBuffer tmp = ByteBuffer.allocate(2).setAutoExpand(true);
tmp.putString(delimiter.getValue(), charset.newEncoder());
tmp.flip();
delimBuf = tmp;
int oldPos = in.position();
int oldLimit = in.limit();
while (in.hasRemaining()) {
byte b = in.get();
if (delimBuf.get(matchCount) == b) {
matchCount++;
if (matchCount == delimBuf.limit()) {
int pos = in.position();
in.limit(pos);
in.position(oldPos);
in.limit(oldLimit);
in.position(pos);
buf.flip();
buf.limit(buf.limit() - matchCount);
try {
out.write(buf.getString(ctx.getDecoder()));
} finally {
buf.clear();
in.position(Math.max(0, in.position() - matchCount));
matchCount = 0;
代码示例来源:origin: org.littleshoot/mina-port
private void readSession(DatagramChannel channel, RegistrationRequest req)
throws Exception {
ByteBuffer readBuf = ByteBuffer
.allocate(((DatagramSessionConfig) req.config
.getSessionConfig()).getReceiveBufferSize());
try {
SocketAddress remoteAddress = channel.receive(readBuf.buf());
if (remoteAddress != null) {
DatagramSessionImpl session = (DatagramSessionImpl) newSession(
remoteAddress, req.address);
readBuf.flip();
ByteBuffer newBuf = ByteBuffer.allocate(readBuf.limit());
newBuf.put(readBuf);
newBuf.flip();
session.increaseReadBytes(newBuf.remaining());
session.getFilterChain().fireMessageReceived(session, newBuf);
}
} finally {
readBuf.release();
}
}
代码示例来源:origin: org.littleshoot/stun-stack
private static UUID createTransactionId()
{
final UUID id = UUID.randomUUID();
final byte[] idBytes = id.getRawBytes();
final ByteBuffer idBuf = ByteBuffer.wrap(idBytes);
// Lower the limit to make room for the magic cookie.
idBuf.limit(idBytes.length - 4);
final ByteBuffer newIdBuf = ByteBuffer.allocate(16);
MinaUtils.putUnsignedInt(newIdBuf, MAGIC_COOKIE);
newIdBuf.put(idBuf);
newIdBuf.flip();
return new UUID(MinaUtils.toByteArray(newIdBuf));
}
代码示例来源:origin: org.littleshoot/mina-port
public void write(ByteBuffer src) {
synchronized (mutex) {
if (closed) {
return;
}
if (buf.hasRemaining()) {
this.buf.compact();
this.buf.put(src);
this.buf.flip();
} else {
this.buf.clear();
this.buf.put(src);
this.buf.flip();
mutex.notifyAll();
}
}
}
代码示例来源:origin: org.littleshoot/mina-util
private static ByteBuffer createBuffer(final ByteBuffer buffer)
{
// We calculate this here because the final split buffer will not
// necessarily have a size equal to the chunk size -- it will
// usually be smaller.
final ByteBuffer data = ByteBuffer.allocate(
buffer.limit() - buffer.position());
data.put(buffer);
data.flip();
return data;
}
代码示例来源:origin: org.littleshoot/mina-util
private static ByteBuffer createBuffer(final ByteBuffer buffer)
{
final ByteBuffer data = ByteBuffer.allocate(
buffer.limit() - buffer.position());
LOG.trace("Created buffer with capacity: "+data.capacity());
data.put(buffer);
data.rewind();
return data;
}
代码示例来源:origin: org.littleshoot/mina-port
public void encode(IoSession session, Object message,
ProtocolEncoderOutput out) throws Exception {
if (!(message instanceof Serializable)) {
throw new NotSerializableException();
}
ByteBuffer buf = ByteBuffer.allocate(64);
buf.setAutoExpand(true);
buf.putObject(message);
int objectSize = buf.position() - 4;
if (objectSize > maxObjectSize) {
buf.release();
throw new IllegalArgumentException(
"The encoded object is too big: " + objectSize + " (> "
+ maxObjectSize + ')');
}
buf.flip();
out.write(buf);
}
}
代码示例来源:origin: org.littleshoot/stun-server
/**
* Creates a new STUN server.
*
* @param codecFactory The factory for creating STUN codecs.
* @param ioHandler The IO handler, often a demuxing handler that
* demultiplexes STUN with the media protocol.
* @param threadName The name of the thread to use.
*/
public AbstractStunServer(final ProtocolCodecFactory codecFactory,
final IoHandler ioHandler, final String threadName) {
ByteBuffer.setUseDirectBuffers(false);
ByteBuffer.setAllocator(new SimpleByteBufferAllocator());
this.codecFactory = codecFactory;
this.ioHandler = ioHandler;
this.threadName = threadName;
}
代码示例来源:origin: org.littleshoot/mina-port
public void encode(IoSession session, Object message,
ProtocolEncoderOutput out) throws Exception {
CharsetEncoder encoder = (CharsetEncoder) session.getAttribute(ENCODER);
if (encoder == null) {
encoder = charset.newEncoder();
session.setAttribute(ENCODER, encoder);
}
String value = message.toString();
ByteBuffer buf = ByteBuffer.allocate(value.length())
.setAutoExpand(true);
buf.putString(value, encoder);
if (buf.position() > maxLineLength) {
throw new IllegalArgumentException("Line length: " + buf.position());
}
buf.putString(delimiter.getValue(), encoder);
buf.flip();
out.write(buf);
}
代码示例来源:origin: org.littleshoot/mina-port
public Object readObject() throws ClassNotFoundException, IOException {
int objectSize = in.readInt();
if (objectSize <= 0) {
throw new StreamCorruptedException("Invalid objectSize: "
+ objectSize);
}
if (objectSize > maxObjectSize) {
throw new StreamCorruptedException("ObjectSize too big: "
+ objectSize + " (expected: <= " + maxObjectSize + ')');
}
ByteBuffer buf = ByteBuffer.allocate(objectSize + 4, false);
buf.putInt(objectSize);
in.readFully(buf.array(), 4, objectSize);
buf.position(0);
buf.limit(objectSize + 4);
Object answer = buf.getObject(classLoader);
buf.release();
return answer;
}
代码示例来源:origin: org.littleshoot/mina-port
buf.put(in);
buf.flip();
} else {
buf = in;
int oldPos = buf.position();
boolean decoded = doDecode(session, buf, out);
if (decoded) {
if (buf.position() == oldPos) {
throw new IllegalStateException(
"doDecode() can't return true when buffer is not consumed.");
if (!buf.hasRemaining()) {
break;
if (buf.hasRemaining()) {
if (usingSessionBuffer)
buf.compact();
else
storeRemainingInSession(buf, session);
代码示例来源:origin: org.littleshoot/mina-port
private void storeRemainingInSession(ByteBuffer buf, IoSession session) {
ByteBuffer remainingBuf = ByteBuffer.allocate(buf.capacity());
remainingBuf.setAutoExpand(true);
remainingBuf.order(buf.order());
remainingBuf.put(buf);
session.setAttribute(BUFFER, remainingBuf);
}
}
代码示例来源:origin: org.littleshoot/mina-port
public void writeObject(Object obj) throws IOException {
ByteBuffer buf = ByteBuffer.allocate(64, false);
buf.setAutoExpand(true);
buf.putObject(obj);
int objectSize = buf.position() - 4;
if (objectSize > maxObjectSize) {
buf.release();
throw new IllegalArgumentException(
"The encoded object is too big: " + objectSize + " (> "
+ maxObjectSize + ')');
}
out.write(buf.array(), 0, buf.position());
buf.release();
}
内容来源于网络,如有侵权,请联系作者删除!