mina接收消息:开始符号,和结束符号问题,TextLineCodecFactory默认是/r/n
< 返回列表时间: 2019-07-30来源:开源中国
HDC调试需求开发(15万预算),能者速来!>>>
mina接收消息:开始符号,和结束符号问题,TextLineCodecFactory默认是/r/n
客户机消息是 STX是开头 ETX是结尾,对应16进制02 03,这时候TextLineCodecFactory需要怎么设置呢?



核心代码:
TextLineCodecFactory tlcf = new TextLineCodecFactory(Charset.forName("gb2312"),new LineDelimiter("STXETX"),new LineDelimiter("STXETX"));
目前收到消息如下:没有正常调用接收消息的messageReceived方法


完整代码:
package com.yice.cloud.websocket;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MinaTimeTest {
private static final int PORT = 9123;

public static void main(String[] args) throws IOException {
//首先,我们为服务端创建IoAcceptor,NioSocketAcceptor是基于NIO的服务端监听器
IoAcceptor acceptor = new NioSocketAcceptor();
//接着,如结构图示,在Acceptor和IoHandler之间将设置一系列的Fliter"\r\n", "\r\n"
//包括记录过滤器和编解码过滤器。其中TextLineCodecFactory是mina自带的文本解编码器
acceptor.getFilterChain().addLast("logger", new LoggingFilter());
TextLineCodecFactory tlcf = new TextLineCodecFactory(Charset.forName("gb2312"),new LineDelimiter("STXETX"),new LineDelimiter("STXETX"));
//CustomProtocolCodecFactory tlcf = new CustomProtocolCodecFactory(Charset.forName("gb2312"));

acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(tlcf));
/*acceptor.getFilterChain().addLast("codec",
new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));*/


//配置事务处理Handler,将请求转由TimeServerHandler处理。
acceptor.setHandler(new TimeServerHandler());
//配置Buffer的缓冲区大小
acceptor.getSessionConfig().setReadBufferSize(2048);
//设置等待时间,每隔IdleTime将调用一次handler.sessionIdle()方法
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
//绑定端口
acceptor.bind(new InetSocketAddress(PORT));
}


static class TimeServerHandler extends IoHandlerAdapter {
private Logger logger = LoggerFactory.getLogger(this.getClass());
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
cause.printStackTrace();
}

public void messageReceived(IoSession session, Object message)
throws Exception {

logger.info("接受消息成功..." + message.toString());
super.messageReceived(session, message);
}

public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
System.out.println("IDLE ==============" + session.getIdleCount(status));
}
}
}



热门排行