当前位置: 首页>>代码示例>>Java>>正文


Java ByteBuffer类代码示例

本文整理汇总了Java中org.apache.mina.common.ByteBuffer的典型用法代码示例。如果您正苦于以下问题:Java ByteBuffer类的具体用法?Java ByteBuffer怎么用?Java ByteBuffer使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


ByteBuffer类属于org.apache.mina.common包,在下文中一共展示了ByteBuffer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: decode

import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
public MessageDecoderResult decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out)
        throws ProtocolCodecException {
    int messageCount = 0;
    while (parseMessage(in, out)) {
        messageCount++;
    }
    if (messageCount > 0) {
        // Mina will compact the buffer because we can't detect a header
        if (in.remaining() < HEADER_PATTERN.length) {
            position = 0;
        }
        return MessageDecoderResult.OK;
    } else {
        // Mina will compact the buffer
        position -= in.position();
        return MessageDecoderResult.NEED_DATA;
    }
}
 
开发者ID:fix-protocol-tools,项目名称:STAFF,代码行数:19,代码来源:FixMessageDecoder.java

示例2: run_startup_configurations

import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
public static void run_startup_configurations() {
    ip = ServerConfig.IP_ADDRESS + ":" + PORT;

    ByteBuffer.setUseDirectBuffers(false);
    ByteBuffer.setAllocator(new SimpleByteBufferAllocator());

    acceptor = new SocketAcceptor();
    final SocketAcceptorConfig cfg = new SocketAcceptorConfig();
    cfg.getSessionConfig().setTcpNoDelay(true);
    cfg.setDisconnectOnUnbind(true);
    cfg.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MapleCodecFactory()));
    players = new PlayerStorage(-10);

    try {
        InetSocketadd = new InetSocketAddress(PORT);
        acceptor.bind(InetSocketadd, new MapleServerHandler(), cfg);
        System.out.println("Cash Shop Server is listening on port " + PORT + ".");
    } catch (final IOException e) {
        System.out.println(" Failed!");
        System.err.println("Could not bind to port " + PORT + ".");
        throw new RuntimeException("Binding failed.", e);
    }
}
 
开发者ID:ergothvs,项目名称:Lucid2.0,代码行数:24,代码来源:CashShopServer.java

示例3: run_startup_configurations

import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
public static final void run_startup_configurations() {
    userLimit = ServerConfig.USER_LIMIT;
    serverName = ServerConfig.SERVER_NAME;
    eventMessage = ServerConfig.EVENT_MSG;
    maxCharacters = ServerConfig.MAX_CHARACTERS;

    ByteBuffer.setUseDirectBuffers(false);
    ByteBuffer.setAllocator(new SimpleByteBufferAllocator());

    acceptor = new SocketAcceptor();
    final SocketAcceptorConfig cfg = new SocketAcceptorConfig();
    cfg.getSessionConfig().setTcpNoDelay(true);
    cfg.setDisconnectOnUnbind(true);
    cfg.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MapleCodecFactory()));

    try {
        InetSocketadd = new InetSocketAddress(8484);
        acceptor.bind(InetSocketadd, new MapleServerHandler(), cfg);
        System.out.println("Login Server is listening on port 8484.");
    } catch (IOException e) {
        System.out.println(" Failed!");
        System.err.println("Could not bind to port 8484: " + e);
    }
}
 
开发者ID:ergothvs,项目名称:Lucid2.0,代码行数:25,代码来源:LoginServer.java

示例4: encode

import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
@Override
public void encode(final IoSession session, final Object message, final ProtocolEncoderOutput out) throws Exception {
    final MapleClient client = (MapleClient) session.getAttribute(MapleClient.CLIENT_KEY);

    if (client != null) {
        final byte[] input = ((MaplePacket) message).getBytes();
        final byte[] unencrypted = new byte[input.length];
        System.arraycopy(input, 0, unencrypted, 0, input.length);

        final byte[] ret = new byte[unencrypted.length + 4];

        final byte[] header = client.getSendCrypto().getPacketHeader(unencrypted.length);
        synchronized(client.getSendCrypto()){
            MapleCustomEncryption.encryptData(unencrypted);
            client.getSendCrypto().crypt(unencrypted);

            System.arraycopy(header, 0, ret, 0, 4);
            System.arraycopy(unencrypted, 0, ret, 4, unencrypted.length);

            final ByteBuffer out_buffer = ByteBuffer.wrap(ret);
            out.write(out_buffer);
        }
    } else { // no client object created yet, send unencrypted (hello)
            out.write(ByteBuffer.wrap(((MaplePacket) message).getBytes()));
    }
}
 
开发者ID:NoetherEmmy,项目名称:intransigentms,代码行数:27,代码来源:MaplePacketEncoder.java

示例5: encode

import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
public void encode(IoSession session, Object message,
		ProtocolEncoderOutput out) throws Exception {
	if(!(message instanceof byte[])){
		throw new Exception("must send byte[]");
	}
	byte[] payload=(byte[]) message;
	ByteBuffer buf = ByteBuffer.allocate(payload.length, false);
       buf.put(payload);
       buf.flip();
       out.write(buf);
       if (isDebugEnabled)
       	LOGGER.debug(TairUtil.toHex(payload));
}
 
开发者ID:alibaba,项目名称:tair-java-client,代码行数:14,代码来源:TairProtocolEncoder.java

示例6: appendDebugInformation

import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
private String appendDebugInformation(ByteBuffer buffer, String text) {
    int mark = buffer.position();
    try {
        StringBuilder sb = new StringBuilder(text);
        sb.append("\nBuffer debug info: ").append(getBufferDebugInfo(buffer));
        buffer.position(0);
        sb.append("\nBuffer contents: ");
        try {
            final byte[] array = new byte[buffer.limit()];
            for(int i = 0; i < array.length; ++i)
                array[i] = buffer.get();
            sb.append(new String(array, "ISO-8859-1"));
        } catch (Exception e) {
            sb.append(buffer.getHexDump());
        }
        text = sb.toString();
    } finally {
        buffer.position(mark);
    }
    return text;
}
 
开发者ID:fix-protocol-tools,项目名称:STAFF,代码行数:22,代码来源:FixMessageDecoder.java

示例7: startsWith

import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
private static boolean startsWith(ByteBuffer buffer, int bufferOffset, byte[] data) {
    try {
        if (bufferOffset + data.length > buffer.limit()) {
            return false;
        }

        //StringBuffer sb = new StringBuffer();
        for (int dataOffset = 0; dataOffset < data.length && bufferOffset < buffer.limit(); dataOffset++, bufferOffset++) {

            byte b = buffer.get(bufferOffset);
            if(b == '\r' && dataOffset > 0 && buffer.get(bufferOffset - 1) == '\u0001') {
                return true;  // EOF io
            }

            byte bPatern = data[dataOffset];
            if (b != bPatern && bPatern != '?') {
                return false;
            }
        }
        return true;
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return false;
}
 
开发者ID:fix-protocol-tools,项目名称:STAFF,代码行数:26,代码来源:FixMessageDecoder.java

示例8: extractMessages

import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
/**
 * Utility to extract messages from a file. This method will return each
 * message found to a provided listener. The message file will also be
 * memory mapped rather than fully loaded into physical memory. Therefore,
 * a large message file can be processed without using excessive memory.
 *
 * @param file
 * @param listener
 * @throws IOException
 * @throws ProtocolCodecException
 */
public void extractMessages(File file, final MessageListener listener) throws IOException,
        ProtocolCodecException {
    // Set up a read-only memory-mapped file
    FileChannel readOnlyChannel = new RandomAccessFile(file, "r").getChannel();
    MappedByteBuffer memoryMappedBuffer = readOnlyChannel.map(FileChannel.MapMode.READ_ONLY, 0,
            (int) readOnlyChannel.size());

    decode(null, ByteBuffer.wrap(memoryMappedBuffer), new ProtocolDecoderOutput() {

        public void write(Object message) {
            listener.onMessage((String) message);
        }

        public void flush() {
            // ignored
        }

    });
}
 
开发者ID:fix-protocol-tools,项目名称:STAFF,代码行数:31,代码来源:FixMessageDecoder.java

示例9: readShortString

import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
public static String readShortString(ByteBuffer buffer)
{
    short length = buffer.getUnsigned();
    if (length == 0)
    {
        return null;
    }
    else
    {
        // this may seem rather odd to declare two array but testing has shown
        // that constructing a string from a byte array is 5 (five) times slower
        // than constructing one from a char array.
        // this approach here is valid since we know that all the chars are
        // ASCII (0-127)
        byte[] stringBytes = new byte[length];
        buffer.get(stringBytes, 0, length);
        char[] stringChars = new char[length];
        for (int i = 0; i < stringChars.length; i++)
        {
            stringChars[i] = (char) stringBytes[i];
        }

        return new String(stringChars);
    }
}
 
开发者ID:wso2,项目名称:andes,代码行数:26,代码来源:EncodingUtils.java

示例10: messageReceived

import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
@Override
public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
       // Decode the bytebuffer and print it to the stdout
       if (enabled && message instanceof ByteBuffer) {
           ByteBuffer byteBuffer = (ByteBuffer) message;
           // Keep current position in the buffer
           int currentPos = byteBuffer.position();
           // Decode buffer
           Charset encoder = Charset.forName("UTF-8");
           CharBuffer charBuffer = encoder.decode(byteBuffer.buf());
           // Print buffer content
           System.out.println(prefix + " - RECV (" + session.hashCode() + "): " + charBuffer);
           // Reset to old position in the buffer
           byteBuffer.position(currentPos);
       }
       // Pass the message to the next filter
       super.messageReceived(nextFilter, session, message);
   }
 
开发者ID:coodeer,项目名称:g3server,代码行数:19,代码来源:RawPrintFilter.java

示例11: writeToBuffer

import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
public void writeToBuffer(ByteBuffer buffer)
{
    final boolean trace = _logger.isDebugEnabled();

    if (trace)
    {
        _logger.debug("FieldTable::writeToBuffer: Writing encoded length of " + getEncodedSize() + "...");
        if (_properties != null)
        {
            _logger.debug(_properties.toString());
        }
    }

    EncodingUtils.writeUnsignedInteger(buffer, getEncodedSize());

    putDataInBuffer(buffer);
}
 
开发者ID:wso2,项目名称:andes,代码行数:18,代码来源:FieldTable.java

示例12: doDecodePI

import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
/**
 * Decodes an AMQP initiation, delegating the decoding to a {@link ProtocolInitiation.Decoder}.
 *
 * @param session The Mina session.
 * @param in      The raw byte buffer.
 * @param out     The Mina object output gatherer to write decoded objects to.
 *
 * @return <tt>true</tt> if the data was decoded, <tt>false<tt> if more is needed and the data should accumulate.
 *
 * @throws Exception If the data cannot be decoded for any reason.
 */
private boolean doDecodePI(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception
{
    boolean enoughData = _piDecoder.decodable(in.buf());
    if (!enoughData)
    {
        // returning false means it will leave the contents in the buffer and
        // call us again when more data has been read
        return false;
    }
    else
    {
        ProtocolInitiation pi = new ProtocolInitiation(in.buf());
        out.write(pi);

        return true;
    }
}
 
开发者ID:wso2,项目名称:andes,代码行数:29,代码来源:AMQDecoder.java

示例13: writeUTF

import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
public void writeUTF(String string) throws JMSException
{
    checkWritable();
    try
    {
        CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
        java.nio.ByteBuffer encodedString = encoder.encode(CharBuffer.wrap(string));
        
        _data.putShort((short)encodedString.limit());
        _data.put(encodedString);
        _changedData = true;
        //_data.putString(string, Charset.forName("UTF-8").newEncoder());
        // we must add the null terminator manually
        //_data.put((byte)0);
    }
    catch (CharacterCodingException e)
    {
        JMSException jmse = new JMSException("Unable to encode string: " + e);
        jmse.setLinkedException(e);
        jmse.initCause(e);
        throw jmse;
    }
}
 
开发者ID:wso2,项目名称:andes,代码行数:24,代码来源:JMSBytesMessage.java

示例14: run_startup_configurations

import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
public static void run_startup_configurations() {
    System.out.print("Loading Cash Shop...");
    ip = ServerConfig.interface_ + ":" + PORT;

    ByteBuffer.setUseDirectBuffers(false);
    ByteBuffer.setAllocator(new SimpleByteBufferAllocator());

    acceptor = new SocketAcceptor();
    final SocketAcceptorConfig cfg = new SocketAcceptorConfig();
    cfg.getSessionConfig().setTcpNoDelay(true);
    cfg.setDisconnectOnUnbind(true);
    cfg.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MapleCodecFactory()));
    players = new PlayerStorage(-10);

    try {
        InetSocketadd = new InetSocketAddress(PORT);
        acceptor.bind(InetSocketadd, new MapleServerHandler(), cfg);
        System.out.println(" Complete!");
        System.out.println("Cash Shop Server is listening on port " + PORT + ".");
    } catch (final IOException e) {
        System.out.println(" Failed!");
        System.err.println("Could not bind to port " + PORT + ".");
        throw new RuntimeException("Binding failed.", e);
    }
}
 
开发者ID:skorch37,项目名称:Asteria,代码行数:26,代码来源:CashShopServer.java

示例15: extractByteMessageContent

import org.apache.mina.common.ByteBuffer; //导入依赖的package包/类
/**
 * Extract ByteMessage from ByteBuffer
 *
 * @param wrapMsgContent ByteBuffer which contains data
 * @param byteMsgContent byte[] of message content
 * @return extracted content as text
 */
private String extractByteMessageContent(ByteBuffer wrapMsgContent, byte[] byteMsgContent) {
    String wholeMsg;
    if (byteMsgContent == null) {
        throw new IllegalArgumentException("byte array must not be null");
    }
    int count = (wrapMsgContent.remaining() >= byteMsgContent.length ?
            byteMsgContent.length :
            wrapMsgContent.remaining());
    if (count == 0) {
        wholeMsg = String.valueOf(-1);
    } else {
        wrapMsgContent.get(byteMsgContent, 0, count);
        wholeMsg = String.valueOf(count);
    }
    return wholeMsg;
}
 
开发者ID:wso2,项目名称:andes,代码行数:24,代码来源:QueueManagementInformationMBean.java


注:本文中的org.apache.mina.common.ByteBuffer类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。