1.客户端和服务器的使用的过滤器不一致
例如:
服务器端:
// 添加编、解码器
ACCEPTOR.getFilterChain().addLast("codec",new ProtocolCodecFilter(new WSFCodecFactory()));
// 设置处理客户端消息的处理类
ACCEPTOR.setHandler(new WSFServerHandler());
ACCEPTOR.getSessionConfig().setReadBufferSize(1024);
ACCEPTOR.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
ACCEPTOR.bind(new InetSocketAddress(Constant.SERVICE_TCP_PORT));
客户端:
NioSocketConnector connector = new NioSocketConnector();
connector.getFilterChain().addLast(
"encode",
new ProtocolCodecFilter(new TextLineCodecFactory(Charset
.forName("UTF-8"), LineDelimiter.WINDOWS.getValue(),
LineDelimiter.WINDOWS.getValue())));
connector.getSessionConfig().setReadBufferSize(2048);
connector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
connector.setConnectTimeoutMillis(30000);
connector.setHandler(new SendMsgClientHandler());
2.解析的规则导致信息无法被服务端正确解析而无法回传值
例如:
@Override
protected boolean doDecode(IoSession session, IoBuffer in,
ProtocolDecoderOutput out) throws Exception {
// 把接收到的 byte 存放到 byte 数组中
byte[] bytes = new byte[in.limit()];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = in.get();
}
// 如果长度小于 16 不予处理:根据需要进行调整
if (bytes.length < Constant.PROTOCOL_LENGTH_WITHOUT_CONTENT) {
in.rewind();
//注意这些地方因为有返回会导致
return false;
}
// 获取数据长度
Short dataLength = shortByte(bytes[1], bytes[2]);
// 获取命令类型
// 取出数据,1.数据的开头、结尾要跟协议定义的一致 2.数据的长度要跟定义的一致
logger.info("命令长度:" + dataLength + ",命令类型:" + bytes[5]);
if (bytes[0] != Constant.PROTOCOL_HEAD
|| bytes[bytes.length - 1] != Constant.PROTOCOL_FOOT
|| bytes.length != dataLength) {
in.rewind();
return false;
}
// 打印日志
logger.info(IoBuffer.wrap(bytes).getHexDump());
// 构造 消息对象
WSFMessage message = new WSFMessage();
out.write(message);
return true;
}
上面代码中的
// 如果长度小于 16 不予处理:根据需要进行调整
if (bytes.length < Constant.PROTOCOL_LENGTH_WITHOUT_CONTENT) {
in.rewind();
//注意这些地方因为有返回会导致
return false;
}
和
if (bytes[0] != Constant.PROTOCOL_HEAD
|| bytes[bytes.length - 1] != Constant.PROTOCOL_FOOT
|| bytes.length != dataLength) {
in.rewind();
return false;
}
会出现客户端发送数据服务器无法正确解析的情况,这些需要注意。