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

The following examples show how to use org.apache.mina.core.buffer.IoBuffer#prefixedDataAvailable() . 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: DataCodecDecoder.java    From oim-fx with MIT License 6 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
	try {
		if (in.prefixedDataAvailable(4, Integer.MAX_VALUE)) {
			in.mark();// 标记当前位置,以便reset
			int size = in.getInt();
			if ((size) > in.remaining()) {// 如果消息内容不够,则重置,相当于不读取size
				in.reset();
				return false;// 接收新数据,以拼凑成完整数据
			}
			byte[] bodyByte = new byte[size];
			in.get(bodyByte, 0, size);
			String xml = new String(bodyByte, charset);
			out.write(xml);
			return true;// 接收新数据,以拼凑成完整数据
		}
	} catch (Exception e) {
		in.sweep();
		logger.error("", e);
	}
	return false;
}
 
Example 2
Source File: CommandDecoder.java    From mina with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    if (in.prefixedDataAvailable(2)) {
        short length = in.getShort();//获取包长

        byte[] bytes = new byte[length];
        in.get(bytes);
        byte[] msgidBytes = new byte[Constants.COMMAND_LENGTH];
        System.arraycopy(bytes, 0, msgidBytes, 0, Constants.COMMAND_LENGTH);
        int msgid = NumberUtils.bytesToInt(msgidBytes);
        if (msgid != 0) {
            //通过工厂方法生成指定消息类型的指令对象
            BaseCommand command = CommandFactory.createCommand(msgid);

            byte[] cmdBodyBytes = new byte[length - Constants.COMMAND_LENGTH];
            System.arraycopy(bytes, Constants.COMMAND_LENGTH, cmdBodyBytes, 0, length - Constants.COMMAND_LENGTH);
            command.bodyFromBytes(cmdBodyBytes);
            out.write(command);
            return true;
        }
    }

    return false;
}
 
Example 3
Source File: CommandDecoder.java    From mina with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    if (in.prefixedDataAvailable(2)) {
        short length = in.getShort();//获取包长

        byte[] bytes = new byte[length];
        in.get(bytes);
        byte[] msgidBytes = new byte[Constants.COMMAND_LENGTH];
        System.arraycopy(bytes, 0, msgidBytes, 0, Constants.COMMAND_LENGTH);
        int msgid = NumberUtils.bytesToInt(msgidBytes);
        if (msgid != 0) {
            //通过工厂方法生成指定消息类型的指令对象
            BaseCommand command = CommandFactory.createCommand(msgid);

            byte[] cmdBodyBytes = new byte[length - Constants.COMMAND_LENGTH];
            System.arraycopy(bytes, Constants.COMMAND_LENGTH, cmdBodyBytes, 0, length - Constants.COMMAND_LENGTH);
            command.bodyFromBytes(cmdBodyBytes);
            out.write(command);
            return true;
        }
    }

    return false;
}
 
Example 4
Source File: RpcRequestDecoder.java    From gameserver with Apache License 2.0 6 votes vote down vote up
/**
 * Decode the RpcRequest
 */
protected boolean doDecode(IoSession session, IoBuffer in,
		ProtocolDecoderOutput out) throws Exception {
	
	if (in.prefixedDataAvailable(HEADER_LENGTH, MAX_LENGTH)) {
		RpcMessage.Builder rpcRequestBuilder = RpcMessage.newBuilder();
		int length = in.getInt();
		byte[] bytes = new byte[length];
		in.get(bytes);
		rpcRequestBuilder.mergeFrom(bytes);
		
		out.write(rpcRequestBuilder.build());
		return true;
	} else {
		// not enough data available
		return false;
	}
}
 
Example 5
Source File: BytesDataDecoder.java    From oim-fx with MIT License 5 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
	try {
		if (in.prefixedDataAvailable(4, Integer.MAX_VALUE)) {
			in.mark();// 标记当前位置,以便reset

			int textSize = in.getInt(); // 读取传送过来的消息的长度。ByteBuf
			int bytesSize = in.getInt();
			int totalSize = (textSize + bytesSize);
			if ((totalSize) > in.remaining()) {// 如果消息内容不够,则重置,相当于不读取size
				in.reset();
				return false;// 接收新数据,以拼凑成完整数据
			}

			BytesData bd = new BytesData();

			byte[] textBytes = new byte[textSize]; // 嗯,这时候,我们读到的长度,满足我们的要求了,把传送过来的数据,取出来吧~~
			in.get(textBytes); //

			byte[] bytes = new byte[bytesSize];
			in.get(bytes); //

			String text = new String(textBytes, charset); // 将byte数据转化为我们需要的对象。伪代码,用什么序列化,自行选择

			bd.setMessage(text);
			bd.setBytes(bytes);
			out.write(bd);
			return true;// 接收新数据,以拼凑成完整数据
		}
	} catch (Exception e) {
		in.sweep();
		logger.error("", e);
	}
	return false;
}
 
Example 6
Source File: ObjectSerializationDecoder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    if (!in.prefixedDataAvailable(4, maxObjectSize)) {
        return false;
    }

    out.write(in.getObject(classLoader));
    return true;
}
 
Example 7
Source File: PrefixedStringDecoder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    if (in.prefixedDataAvailable(prefixLength, maxDataLength)) {
        String msg = in.getPrefixedString(prefixLength, charset.newDecoder());
        out.write(msg);
        return true;
    }

    return false;
}
 
Example 8
Source File: TestTupleDecoder.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
/**
 * Decode bytes an attribute at a time, once enough information exists to
 * maintain a tuple This code maintains state in the session as attributes,
 * namely:
 * <UL>
 * <LI>tuple - The partially initialized tuple to be sent to the next
 * handler in the chain.
 * <LI>attributeIndex - The next attribute to be decoded
 * </UL>
 */
@Override
protected boolean doDecode(IoSession session, IoBuffer in,
        ProtocolDecoderOutput out) throws Exception {

    Integer testerId = null;

    if (!session.containsAttribute("testerId")) {
        if (in.remaining() < 4)
            return false;

        testerId = in.getInt();
    }

    if (!in.prefixedDataAvailable(4)) {
        if (testerId != null)
            session.setAttribute("testerId", testerId);
        return false;
    }

    if (testerId == null) {
        testerId = (Integer) session.removeAttribute("testerId");
    }

    int tupleLength = in.getInt();

    byte[] tupleData = new byte[tupleLength];
    in.get(tupleData);

    out.write(new TestTuple(testerId, tupleData));

    return in.remaining() >= 4;
}
 
Example 9
Source File: AIProtobufDecoder.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 * Decode the message.
 */
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
	// Make sure all the header bytes are ready.
	if ( !in.prefixedDataAvailable(HEADER_LENGTH, MAX_LENGTH) ) {
    return false;
	}
	
	byte[] bytes = new byte[in.getInt()];
	in.get(bytes);
	
	AIMessage aiMessage = AIMessage.parseFrom(bytes);
	
	ByteString sessionBytes = aiMessage.getSession();
	ByteString contentBytes = aiMessage.getContent();
	
	if ( sessionBytes != null && contentBytes != null) {
		SessionKey sessionKey = SessionKey.createSessionKey(sessionBytes.toByteArray());
		XinqiMessage xinqiMessage = XinqiMessage.fromByteArray(contentBytes.toByteArray());
		
		if ( xinqiMessage != null ) {
			SessionAIMessage sessionMessage = new SessionAIMessage();
			sessionMessage.setSessionKey(sessionKey);
			sessionMessage.setMessage(xinqiMessage);
			out.write(sessionMessage);
		}
	} else {
		logger.debug("AIProtocolDecoder sessionBytes or contentBytes is null");
	}
	return true;
}
 
Example 10
Source File: ProtobufDecoder.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 * Decode the XinqiMessage from byte array.
 * @param in
 * @return
 * @throws InvalidProtocolBufferException 
 */
public static final XinqiMessage decodeXinqiMessage(IoBuffer in) 
		throws InvalidProtocolBufferException {
	
	// Make sure all the header bytes are ready.
	if ( !in.prefixedDataAvailable(HEADER_LENGTH, MAX_LENGTH) ) {
    return null;
	}
	
	int length = in.getInt() - 6;
	int type = in.getShort();
	XinqiMessage message = new XinqiMessage();
	//XinqiMessage
	message.type = type;
	message.index = in.getInt();
	byte[] array = new byte[length];
	in.get(array);
	if ( logger.isDebugEnabled() ) {
		logger.debug("length:"+length+", type:"+message.type+", index:"+message.index);
	}
	
	MessageLite request = IdToMessage.idToMessage(message.type);
	
	if ( request == null ) {
		logger.warn("No id found for message type. return empty message. ");
		return message;
	}
	
	request = request.newBuilderForType().mergeFrom(array).build();

	message.payload = request;
	
	return message;
}
 
Example 11
Source File: SessionMessageDecoder.java    From gameserver with Apache License 2.0 4 votes vote down vote up
/**
 * Decode the message.
 */
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
	SessionMessage sessionMessage = (SessionMessage) session.getAttribute(DECODER_STATE_KEY);
	if ( sessionMessage == null ) {
		sessionMessage = new SessionMessage();
		session.setAttribute(DECODER_STATE_KEY, sessionMessage);
	}
	
	// Make sure the sessionkey in the header bytes are ready.
	if ( !in.prefixedDataAvailable(HEADER_LENGTH, MAX_LENGTH) ) {
    return false;
	}
	int sessionKeyLength = in.getShort();
	byte[] sessionRawBytes = new byte[sessionKeyLength];
	in.get(sessionRawBytes);
	SessionKey sessionKey = SessionKey.createSessionKey(sessionRawBytes);
	sessionMessage.setSessionkey(sessionKey);
	
	// Make sure the xinqimessage in the header bytes are ready.
	if ( !in.prefixedDataAvailable(HEADER_LENGTH, MAX_LENGTH) ) {
    return false;
	}
	
	int xinqiMessageLength = in.getShort()-6;
	XinqiMessage message = new XinqiMessage();
	
	message.type = in.getShort();
	message.index = in.getInt();
	if ( log.isDebugEnabled() ) {
		log.debug("XinqiMessage length:"+xinqiMessageLength+", type:"+message.type+", index:"+message.index);
	}
	
	MessageLite request = IdToMessage.idToMessage(message.type);
	if ( request == null ) {
		if ( log.isWarnEnabled() ) {
			log.warn("No id found for message type. return null. ");
		}
		return false;
	}
	
	request = request.newBuilderForType().mergeFrom(in.slice().array(), sessionKeyLength + 10 , xinqiMessageLength).build();

	in.skip(xinqiMessageLength);
	if ( log.isDebugEnabled() ) {
		log.debug("Message:"+request.getClass().getName()+"["+request+"]");
	}
	message.payload = request;
	if ( log.isDebugEnabled() ) {
		log.debug("Response["+message.toString()+"]");
	}
	
	sessionMessage.setMessage(message);
	
	out.write(sessionMessage);
	return true;
}
 
Example 12
Source File: SessionMessageRawDecoder.java    From gameserver with Apache License 2.0 4 votes vote down vote up
/**
 * Decode the message.
 */
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
	SessionRawMessage sessionMessage = (SessionRawMessage) session.getAttribute(DECODER_STATE_KEY);
	DecoderStage stage = (DecoderStage) session.getAttribute(DECODER_STAGE_KEY);
	if ( sessionMessage == null ) {
		sessionMessage = new SessionRawMessage();
		session.setAttribute(DECODER_STATE_KEY, sessionMessage);
	}
	if ( stage == null ) {
		stage = DecoderStage.DECODE_SESSION_KEY;
		session.setAttribute(DECODER_STAGE_KEY, stage);
	}
	
	switch ( stage ) {
		case DECODE_SESSION_KEY:
			// Make sure the sessionkey in the header bytes are ready.
			if ( !in.prefixedDataAvailable(SESSION_LENGTH, MAX_LENGTH) ) {
		    return false;
			}
			int sessionKeyLength = in.getShort() & 0xFFFF;
			byte[] sessionRawBytes = new byte[sessionKeyLength];
			in.get(sessionRawBytes);
			SessionKey sessionKey = SessionKey.createSessionKey(sessionRawBytes);
			sessionMessage.setSessionkey(sessionKey);
			session.setAttribute(DECODER_STAGE_KEY, DecoderStage.DECODE_RAW);
			
		case DECODE_RAW:
			// Make sure the xinqimessage in the header bytes are ready.
			if ( !in.prefixedDataAvailable(RAW_LENGTH, RAW_MAX_LENGTH) ) {
		    return false;
			}
			int rawLength = in.getInt();
			if ( log.isDebugEnabled() ) {
				log.debug("RawMessage length:"+rawLength);
			}
			byte[] rawMessage = new byte[rawLength];
			in.get(rawMessage);
			
			sessionMessage.setRawMessage(rawMessage);
			out.write(sessionMessage);
			
			session.setAttribute(DECODER_STATE_KEY, null);
			session.setAttribute(DECODER_STAGE_KEY, null);
			return true;
		default:
			break;
	}
	
	return false;
}
 
Example 13
Source File: ProtobufDecoder.java    From gameserver with Apache License 2.0 4 votes vote down vote up
/**
	 * Decode the XinqiMessage from byte array.
	 * @param in
	 * @return
	 * @throws InvalidProtocolBufferException 
	 */
	public static final XinqiMessage decodeXinqiMessage(IoBuffer in) 
			throws InvalidProtocolBufferException {
		
		// Make sure all the header bytes are ready.
		if ( !in.prefixedDataAvailable(HEADER_LENGTH, MAX_LENGTH) ) {
	    return null;
		}
		
		int length = in.getInt() - 6;
		int type = in.getShort();
		XinqiMessage message = new XinqiMessage();
		//XinqiMessage
		message.type = type;
		message.index = in.getInt();
		byte[] array = new byte[length];
		in.get(array);
		if ( log.isDebugEnabled() ) {
			log.debug("length:"+length+", type:"+message.type+", index:"+message.index);
		}
		
		MessageLite request = IdToMessage.idToMessage(message.type);
		
		if ( request == null ) {
			if ( log.isWarnEnabled() ) {
				log.warn("No id found for message type. return empty message. ");
			}
			//Note: return an empty message rather than null so that
			//next messages can be parsed.
			return message;
		}
		
		request = request.newBuilderForType().mergeFrom(array).build();

//			in.skip(length);
		if ( log.isDebugEnabled() ) {
			log.debug("DecodedMessage:"+request.getClass().getName()+"[\n"+request+"]");
		}
		message.payload = request;
		if ( log.isDebugEnabled() ) {
			log.debug("XinqiMessage:[\n"+message.toString()+"]");
		}
		
		return message;
	}