Java Code Examples for org.apache.mina.core.buffer.IoBuffer#putShort()

The following examples show how to use org.apache.mina.core.buffer.IoBuffer#putShort() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProtocolEncoderImpl.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
protected IoBuffer createMessage ( final IoSession session, final byte command, final boolean longMessage )
{
    final IoBuffer data = IoBuffer.allocate ( 3 );
    data.setAutoExpand ( true );

    if ( Sessions.isLittleEndian ( session ) )
    {
        data.order ( ByteOrder.LITTLE_ENDIAN );
    }

    data.put ( (byte)0x12 );
    data.put ( (byte)0x02 );
    data.put ( command );
    if ( longMessage )
    {
        data.putShort ( (short)0 );
    }
    return data;
}
 
Example 2
Source File: DaveFilter.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
private void encodeHeader ( final DaveMessage message, final IoBuffer data, final byte type )
{
    // == PDU header
    data.put ( PACKET_START_MAGIC );
    data.put ( type );
    data.put ( (byte)0 );
    data.put ( (byte)0 );
    data.putShort ( (short)0 ); // req nr

    data.putShort ( (short)0 ); // parameter len
    data.putShort ( (short)0 ); // data len

    if ( type == 2 || type == 3 )
    {
        data.put ( (byte)0 );
        data.put ( (byte)0 );
    }
}
 
Example 3
Source File: MessageUtil.java    From CXTouch with GNU General Public License v3.0 6 votes vote down vote up
public static int writeString(String text, IoBuffer buffer, LengthType lenType, Charset charset) {
    byte[] data = text == null ? null : text.getBytes(charset);
    int length = text == null ? -1 : data.length;
    int byteCount = length == -1 ? 0 : length;
    if (lenType == LengthType.INT) {
        buffer.putInt(length);
        byteCount += 4;
    } else if (lenType == LengthType.SHORT) {
        buffer.putShort((short)length);
        byteCount += 2;
    } else if (lenType == LengthType.BYTE) {
        buffer.put((byte)length);
        byteCount += 1;
    } else {
        buffer.putInt(length);
        byteCount += 4;
    }

    if (length  <= 0) {
        return byteCount;
    }

    buffer.put(data);

    return byteCount;
}
 
Example 4
Source File: TPKTFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void filterWrite ( final NextFilter nextFilter, final IoSession session, final WriteRequest writeRequest ) throws Exception
{
    // we only handle IoBuffers
    if ( writeRequest.getMessage () instanceof IoBuffer )
    {
        final IoBuffer inData = (IoBuffer)writeRequest.getMessage ();
        final IoBuffer outData = IoBuffer.allocate ( inData.remaining () + 4 );

        // put the version, the reserved
        outData.put ( (byte)this.version );
        outData.put ( (byte)0 );

        // and the data length
        outData.putShort ( (short) ( inData.remaining () + 4 ) );

        // append the data itself
        outData.put ( inData );

        outData.flip ();

        logger.debug ( "TPKT out: {}", outData );

        // pass on data buffer
        nextFilter.filterWrite ( session, new WriteRequestWrapper ( writeRequest ) {
            @Override
            public Object getMessage ()
            {
                return outData;
            }
        } );
    }
    else
    {
        nextFilter.filterWrite ( session, writeRequest );
    }
}
 
Example 5
Source File: ScreenVideo.java    From red5-io with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public IoBuffer getKeyframe() {
    IoBuffer result = IoBuffer.allocate(1024);
    result.setAutoExpand(true);

    // Header
    result.put((byte) (FLV_FRAME_KEY | VideoCodec.SCREEN_VIDEO.getId()));

    // Frame size
    result.putShort((short) this.widthInfo);
    result.putShort((short) this.heightInfo);

    // Get compressed blocks
    byte[] tmpData = new byte[this.blockDataSize];
    int pos = 0;
    for (int idx = 0; idx < this.blockCount; idx++) {
        int size = this.blockSize[idx];
        if (size == 0) {
            // this should not happen: no data for this block
            return null;
        }

        result.putShort((short) size);
        System.arraycopy(this.blockData, pos, tmpData, 0, size);
        result.put(tmpData, 0, size);
        pos += this.blockDataSize;
    }

    result.rewind();
    return result;
}
 
Example 6
Source File: SessionMessageRawEncoder.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 * Check the id value and set it into context attachment.
 */
@Override
public void encode(IoSession session, Object msg, ProtocolEncoderOutput out) 
		throws Exception {
	
	SessionRawMessage sessionMessage = null;
	if ( msg instanceof SessionRawMessage ) {
		sessionMessage = (SessionRawMessage)msg;
	}
	
	byte[] rawMessage = sessionMessage.getRawMessage();
	if (rawMessage != null) {
		byte[] sessionKeyBytes = sessionMessage.getSessionkey().getRawKey();
		IoBuffer body = IoBuffer.allocate(SESSION_HEADER_LENGTH + sessionKeyBytes.length + RAW_HEADER_LENGTH + rawMessage.length);
		/*
		 * +---------------+               +-------------------+-----------------+--------------------------+--------------------+
		 * | Message Data  |-------------->| sessionkey length |    sessionkey   |        Raw Length        |     Any Raw Data   |
		 * |  (300 bytes)  |               |       0xFFFF      |      (bytes)    |        0xFFFFFFFF        |     (300 bytes)    |
		 * +---------------+               +-------------------+-----------------+--------------------------+--------------------+
		 */
		body.putShort((short)sessionKeyBytes.length);
		body.put(sessionKeyBytes);
		body.putInt(rawMessage.length);
		body.put(rawMessage);
		body.flip();
		out.write(body);
	
	} else {
		if ( log.isDebugEnabled() ) {
			log.debug("Raw message's content is empty.");
		}
	}
}
 
Example 7
Source File: CommandEncoder.java    From mina with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    BaseCommand command = (BaseCommand) message;
    byte[] bytes = command.toBytes();
    IoBuffer buf = IoBuffer.allocate(bytes.length, false);

    buf.setAutoExpand(true);
    buf.putShort( (short) bytes.length );
    buf.put(bytes);

    buf.flip();
    out.write(buf);
}
 
Example 8
Source File: CommandEncoder.java    From mina with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    BaseCommand command = (BaseCommand) message;
    byte[] bytes = command.toBytes();
    IoBuffer buf = IoBuffer.allocate(bytes.length, false);

    buf.setAutoExpand(true);
    buf.putShort( (short) bytes.length );
    buf.put(bytes);

    buf.flip();
    out.write(buf);
}
 
Example 9
Source File: ArduinoCodec.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void encodeHeader ( final IoBuffer data, final CommonMessage message )
{
    data.putShort ( (short)1202 );
    data.put ( (byte)0x01 );
    data.putInt ( message.getSequence () );
    data.put ( message.getCommandCode ().getCommandCode () );
}
 
Example 10
Source File: ModbusRtuEncoder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void encode ( final IoSession session, final Object message, final ProtocolEncoderOutput out ) throws Exception
{
    logger.debug ( "Encoding: {}", message );
    final Pdu request = (Pdu)message;

    final IoBuffer buffer = IoBuffer.allocate ( request.getData ().remaining () + 3 );
    buffer.setAutoExpand ( true );

    final IoBuffer pdu = request.getData ();

    // put slave id
    buffer.put ( request.getUnitIdentifier () );
    // put data
    buffer.put ( pdu );

    // make and put crc
    final int crc = Checksum.crc16 ( buffer.array (), 0, pdu.limit () + 1 ); // including slave address
    buffer.order ( ByteOrder.LITTLE_ENDIAN );
    buffer.putShort ( (short)crc );

    buffer.flip ();

    logger.trace ( "Encoded to: {}", buffer );

    out.write ( buffer );
}
 
Example 11
Source File: DaveFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void finishEncode ( final IoBuffer data, final short parameterLen, final short dataLen )
{
    // set parameter len
    data.putShort ( 6, parameterLen );
    // set data len
    data.putShort ( 8, dataLen );
}
 
Example 12
Source File: DaveFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Encode the request address in the parameters area
 * 
 * @param data
 * @param request
 */
private void encodeAddress ( final IoBuffer data, final Request request )
{
    data.put ( (byte)0x12 );
    data.put ( (byte)0x0a ); // could be the length of the parameter
    data.put ( (byte)0x10 );

    data.put ( request.getType ().getType () );

    data.putShort ( request.getCount () ); // length in bytes
    data.putShort ( request.getBlock () ); // DB number
    data.put ( request.getArea () );
    data.putMediumInt ( request.getStart () * startFactor ( request ) ); // start address in bits
}
 
Example 13
Source File: ScreenVideo2.java    From red5-io with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public IoBuffer getKeyframe() {
    IoBuffer result = IoBuffer.allocate(blockDataSize + 11);
    result.setAutoExpand(true);
    // Header
    result.put((byte) (FLV_FRAME_KEY | VideoCodec.SCREEN_VIDEO2.getId()));
    // Frame size
    result.putShort((short) widthInfo);
    result.putShort((short) heightInfo);
    // reserved (6) has iframeimage (1) has palleteinfo (1)
    result.put(specInfo1);
    // Get compressed blocks
    byte[] tmpData = new byte[blockDataSize];
    int pos = 0;
    for (int idx = 0; idx < blockCount; idx++) {
        int size = blockSize[idx];
        if (size == 0) {
            // this should not happen: no data for this block
            return null;
        }
        result.putShort((short) (size + 1));
        // IMAGEFORMAT
        // reserved(3) color depth(2) has diff blocks(1)
        // ZlibPrimeCompressCurrent(1) ZlibPrimeCompressPrevious (1)
        result.put(specInfo2);
        System.arraycopy(blockData, pos, tmpData, 0, size);
        result.put(tmpData, 0, size);
        pos += blockDataSize;
    }
    result.rewind();
    return result;
}
 
Example 14
Source File: MinaProtocolEncoder.java    From jforgame with Apache License 2.0 5 votes vote down vote up
private IoBuffer writeMessage(Message message) {
		// ----------------消息协议格式-------------------------
		// packetLength | moduleId | cmd  | body
		// int             short     byte  byte[]

		IoBuffer buffer = IoBuffer.allocate(CodecContext.WRITE_CAPACITY);
		buffer.setAutoExpand(true);

		// 写入具体消息的内容
		IMessageEncoder msgEncoder = SerializerHelper.getInstance().getEncoder();
		byte[] body = msgEncoder.writeMessageBody(message);
		// 消息元信息常量3表示消息body前面的两个字段,一个short表示module,一个byte表示cmd,
		final int metaSize = 3;
		// 消息内容长度
		buffer.putInt(body.length + metaSize);
		short moduleId = message.getModule();
		byte cmd = message.getCmd();
		// 写入module类型
		buffer.putShort(moduleId);
		// 写入cmd类型
		buffer.put(cmd);
	
		buffer.put(body);
//		// 回到buff字节数组头部
		buffer.flip();

		return buffer;
	}
 
Example 15
Source File: RTMPProtocolEncoder.java    From red5-server-common with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
public IoBuffer encodePing(Ping ping) {
    int len;
    short type = ping.getEventType();
    switch (type) {
        case Ping.CLIENT_BUFFER:
            len = 10;
            break;
        case Ping.PONG_SWF_VERIFY:
            len = 44;
            break;
        default:
            len = 6;
    }
    final IoBuffer out = IoBuffer.allocate(len);
    out.putShort(type);
    switch (type) {
        case Ping.STREAM_BEGIN:
        case Ping.STREAM_PLAYBUFFER_CLEAR:
        case Ping.STREAM_DRY:
        case Ping.RECORDED_STREAM:
        case Ping.PING_CLIENT:
        case Ping.PONG_SERVER:
        case Ping.BUFFER_EMPTY:
        case Ping.BUFFER_FULL:
            out.putInt(ping.getValue2().intValue());
            break;
        case Ping.CLIENT_BUFFER:
            if (ping instanceof SetBuffer) {
                SetBuffer setBuffer = (SetBuffer) ping;
                out.putInt(setBuffer.getStreamId());
                out.putInt(setBuffer.getBufferLength());
            } else {
                out.putInt(ping.getValue2().intValue());
                out.putInt(ping.getValue3());
            }
            break;
        case Ping.PING_SWF_VERIFY:
            break;
        case Ping.PONG_SWF_VERIFY:
            out.put(((SWFResponse) ping).getBytes());
            break;
    }
    // this may not be needed anymore
    if (ping.getValue4() != Ping.UNDEFINED) {
        out.putInt(ping.getValue4());
    }
    return out;
}
 
Example 16
Source File: ShortIntegerType.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void putValue ( final IoBuffer slice, final Variant value )
{
    slice.putShort ( makeValue ( value ) );
}
 
Example 17
Source File: ProtocolEncoderImpl.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void encode ( final IoSession session, final Object message, final ProtocolEncoderOutput out ) throws Exception
{
    IoBuffer data = null;
    if ( message instanceof Hello )
    {
        data = createMessage ( session, Messages.MC_HELLO, true );

        data.put ( (byte)0x01 ); // version

        data.putShort ( ( (Hello)message ).getNodeId () );
        data.putEnumSetShort ( ( (Hello)message ).getFeatures () );

        data.putUnsignedShort ( 3, data.position () - 3 ); // fill length
    }
    else if ( message instanceof Welcome )
    {
        data = createMessage ( session, Messages.MC_WELCOME, true );

        // put bit set
        data.putEnumSetShort ( ( (Welcome)message ).getFeatures () );
        encodeProperties ( data, ( (Welcome)message ).getProperties () );

        data.putUnsignedShort ( 3, data.position () - 3 ); // fill length
    }
    else if ( message instanceof ReadAll )
    {
        data = createMessage ( session, Messages.MC_READ_ALL, false );

    }
    else if ( message instanceof DataUpdate )
    {
        data = createMessage ( session, Messages.MC_DATA_UPDATE, true );

        data.putUnsignedShort ( ( (DataUpdate)message ).getEntries ().size () );
        // put values
        for ( final DataUpdate.Entry entry : ( (DataUpdate)message ).getEntries () )
        {
            encodeEntry ( session, data, entry );
        }

        data.putUnsignedShort ( 3, data.position () - 3 ); // fill length
    }
    else if ( message instanceof SubscribeBrowse )
    {
        data = createMessage ( session, Messages.MC_START_BROWSE, false );
    }
    else if ( message instanceof UnsubscribeBrowse )
    {
        data = createMessage ( session, Messages.MC_STOP_BROWSE, false );
    }
    else if ( message instanceof BrowseAdded )
    {
        data = createMessage ( session, Messages.MC_NS_ADDED, true );

        // put browse update
        encodeBrowseUpdate ( session, message, data );

        data.putUnsignedShort ( 3, data.position () - 3 ); // fill length
    }
    else if ( message instanceof WriteCommand )
    {
        data = createMessage ( session, Messages.MC_WRITE_COMMAND, true );

        data.putUnsignedShort ( ( (WriteCommand)message ).getRegisterNumber () );
        data.putInt ( ( (WriteCommand)message ).getOperationId () );
        encodeVariant ( session, data, ( (WriteCommand)message ).getValue () );

        data.putUnsignedShort ( 3, data.position () - 3 ); // fill length
    }
    else if ( message instanceof WriteResult )
    {
        data = createMessage ( session, Messages.MC_WRITE_RESULT, true );

        data.putInt ( ( (WriteResult)message ).getOperationId () );
        data.putUnsignedShort ( ( (WriteResult)message ).getErrorCode () );

        data.putPrefixedString ( ( (WriteResult)message ).getErrorMessage (), Sessions.getCharsetEncoder ( session ) );

        data.putUnsignedShort ( 3, data.position () - 3 ); // fill length
    }

    if ( data != null )
    {
        data.flip ();
        out.write ( data );
    }
    else
    {
        throw new ProtocolCodecException ( String.format ( "Message %s is not supported", message.getClass ().getName () ) );
    }
}
 
Example 18
Source File: Int16Accessor.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void put ( final IoBuffer data, final Short value )
{
    data.putShort ( value );
}
 
Example 19
Source File: WebSocketEncoder.java    From red5-websocket with Apache License 2.0 4 votes vote down vote up
public static IoBuffer encodeOutgoingData(Packet packet) {
    log.debug("encode outgoing: {}", packet);
    // get the payload data
    IoBuffer data = packet.getData();
    // get the frame length based on the byte count
    int frameLen = data.limit();
    // start with frame length + 2b (header info)
    IoBuffer buffer = IoBuffer.allocate(frameLen + 2, false);
    buffer.setAutoExpand(true);
    // set the proper flags / opcode for the data
    byte frameInfo = (byte) (1 << 7);
    switch (packet.getType()) {
        case TEXT:
            if (log.isTraceEnabled()) {
                log.trace("Encoding text frame  \r\n{}", new String(packet.getData().array()));
            }
            frameInfo = (byte) (frameInfo | 1);
            break;
        case BINARY:
            log.trace("Encoding binary frame");
            frameInfo = (byte) (frameInfo | 2);
            break;
        case CLOSE:
            frameInfo = (byte) (frameInfo | 8);
            break;
        case CONTINUATION:
            frameInfo = (byte) (frameInfo | 0);
            break;
        case PING:
            log.trace("ping out");
            frameInfo = (byte) (frameInfo | 9);
            break;
        case PONG:
            log.trace("pong out");
            frameInfo = (byte) (frameInfo | 0xa);
            break;
        default:
            break;
    }
    buffer.put(frameInfo);
    // set the frame length
    log.trace("Frame length {} ", frameLen);
    if (frameLen <= 125) {
        buffer.put((byte) ((byte) frameLen & (byte) 0x7F));
    } else if (frameLen > 125 && frameLen <= 65535) {
        buffer.put((byte) ((byte) 126 & (byte) 0x7F));
        buffer.putShort((short) frameLen);
    } else {
        buffer.put((byte) ((byte) 127 & (byte) 0x7F));
        buffer.putLong((int) frameLen);
    }
    buffer.put(data);
    buffer.flip();
    if (log.isTraceEnabled()) {
        log.trace("Encoded: {}", buffer);
    }
    return buffer;
}
 
Example 20
Source File: ShortFieldTypeHandler.java    From CXTouch with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void encode(Short value, IoBuffer outBuffer) {
    short val = value;
    outBuffer.put(getType());
    outBuffer.putShort(val);
}