// 重写基类的方法,当消息到达时触发,这里收到消息后,在控制台输出收到的内容,并原样返回了客户端 public override void ChannelRead(IChannelHandlerContext context, object message) { try { var buf = message as IByteBuffer; // 读取完整消息到字节数组 int remaining = buf.ReadableBytes; byte[] messageBytes = new byte[remaining]; buf.GetBytes(0, messageBytes); // 解析消息字节数组为JT808Message对象 JT808Message result = JT808ProtoDecoder.Decode(messageBytes); // 网关接收数据时间 //string gatewaytime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); //消息正文 //byte[] cmdconent = result.MsgBody; result.channel = context; msgProcessService.processMessageData(result); } catch (Exception ex) { logger.Error(ex, "解析数据时出错{0}", ex.Message); } }
/// <summary> /// 将消息按JT/T 808协议进行编码为字节数组 /// </summary> /// <returns></returns> public byte[] Encode() { if (MsgHeader == null) { throw new Exception("Field: msgHead cannot be null."); } // 消息头编码 byte[] msgHeadBytes = MsgHeader.Encode(); // body byte[] msgBodyBytes = null; if (MsgBody != null) { msgBodyBytes = MsgBody; } // 构建消息(不包含校验码和头尾标识) byte[] message = null; if (msgBodyBytes != null) { ByteBuffer msgbuf = ByteBuffer.Allocate( msgHeadBytes.Length + msgBodyBytes.Length); msgbuf.Put(msgHeadBytes); msgbuf.Put(msgBodyBytes); message = msgbuf.Array(); } else { message = msgHeadBytes; } // 计算校验码 byte checkCode = JT808ProtoDecoder.CheckCode(message); ByteBuffer checkedBuffer = ByteBuffer.Allocate(message.Length + 1); checkedBuffer.Put(message); checkedBuffer.Put(checkCode); byte[] checkedMessage = checkedBuffer.Array(); // 转义 byte[] escapedMessage = JT808ProtoDecoder.Escape(checkedMessage); // 增加标识位 ByteBuffer buffer = ByteBuffer.Allocate(escapedMessage.Length + 2); buffer.Put(JT808Constant.PKG_DELIMITER); buffer.Put(escapedMessage); buffer.Put(JT808Constant.PKG_DELIMITER); return(buffer.Array()); }
/// <summary> /// 编码消息头为字节数组 /// </summary> /// <returns></returns> public byte[] Encode() { int capacity = 12; byte[] splitInfoBytes = null; if (SplitInfo != null) { splitInfoBytes = SplitInfo.Encode(); capacity += splitInfoBytes.Length; } if (MsgBodyAttr == null) { throw new Exception("Field: msgBodyAttr cannot be null."); } ByteBuffer buffer = ByteBuffer.Allocate(capacity); buffer.PutShort(MessageId); buffer.Put(MsgBodyAttr.Encode()); // mobile if (TerminalId.Length > JT808Constant.MAX_MOBILE_LENGTH) { throw new Exception( "Field: mobile=" + TerminalId + ", but max allowable value is " + JT808Constant.MAX_MOBILE_LENGTH + "."); } buffer.Put(JT808ProtoDecoder.Mobile2bcd6(TerminalId)); buffer.PutShort(this.MessageSerial); if (splitInfoBytes != null) { buffer.Put(splitInfoBytes); } return(buffer.Array()); }