/// <summary> /// 数据处理 /// </summary> /// <param name="state"></param> public static void OnReceiveData(ClientState state) { ByteArray readBuff = state.readBuff; //消息长度 if (readBuff.length <= 2) { return; } //消息体长度 int readIdx = readBuff.readIdx; byte[] bytes = readBuff.bytes; Int16 bodyLength = (Int16)((bytes[readIdx + 1] << 8) | bytes[readIdx]); if (readBuff.length < bodyLength) { return; } readBuff.readIdx += 2; //解析协议名 int nameCount = 0; string protoName = ProtocolBase.DecodeName(readBuff.bytes, readBuff.readIdx, out nameCount); if (protoName == "") { Console.WriteLine("OnReceiveData MsgBase.DecodeName fail"); Close(state); return; } readBuff.readIdx += nameCount; //解析协议体 int bodyCount = bodyLength - nameCount; if (bodyCount <= 0) { Console.WriteLine("OnReceiveData fail, bodyCount <=0 "); Close(state); return; } ProtocolBase msgBase = ProtocolBase.Decode(protoName, readBuff.bytes, readBuff.readIdx, bodyCount); readBuff.readIdx += bodyCount; readBuff.CheckAndMoveBytes(); //分发消息 MethodInfo mi = typeof(MsgHandler).GetMethod(protoName); object[] o = { state, msgBase }; Console.WriteLine("Receive " + protoName); if (mi != null) { mi.Invoke(null, o); } else { Console.WriteLine("OnReceiveData Invoke fail " + protoName); } //继续读取消息 if (readBuff.length > 2) { OnReceiveData(state); } }