/// <summary> /// 将收到的数据写入 /// </summary> /// <param name="buffer">收到的数据缓存</param> /// <param name="offset">从字节偏移处拷贝</param> /// <param name="count">写入的长度</param> public bool WriteData(byte[] buffer, int offset, int count) { //先锁定,否则字节流的顺序未必会是正确的顺序 lock (this) { //一定要在系统设计时避免大的命令包,过长的数据拆分成小指令包发送 //这个缓冲一定要避免越界, 各个分系统之间一定要设计好指定包的最大长度 //1.首先判断当前是否正在等待数据 if (IsWaitingData) { int copyCount = (count >= (_PacketDataSize - PacketDataHaveSize)) ? _PacketDataSize - PacketDataHaveSize : count; if (copyCount > 0) { CopyBytes(PacketBytes, PacketDataHaveSize, buffer, offset, copyCount); PacketDataHaveSize += (Int32)copyCount; } //判断命令包的数据是否接收完毕, 否则继续等待 if (PacketDataHaveSize >= _PacketDataSize) { bool eventReturn = true; //通知外部事件处理 eventReturn = TCPHandleMsgManager.HandleMsg(this.PacketCmdID, this.GetPacketBytes(), this.PacketDataSize); //清空当前的状态 _PacketCmdID = 0; _PacketDataSize = 0; PacketDataHaveSize = 0; IsWaitingData = false; CmdHeaderSize = 0; if (!eventReturn) //处理失败,要求关闭连接 { //return false;//消息类型太多没注册,暂时屏蔽掉这个错误。 } //处理剩余的字节 if (count > copyCount) { //改变参数 offset += copyCount; count -= copyCount; //接收数据(递归实现, 简单) return(WriteData(buffer, offset, count)); } } return(true); } else { //正在等待接收命令头 int copyLeftSize = count > (8 - CmdHeaderSize) ? (8 - CmdHeaderSize) : count; CopyBytes(CmdHeaderBuffer, CmdHeaderSize, buffer, offset, copyLeftSize); CmdHeaderSize += copyLeftSize; if (CmdHeaderSize < 8) { return(true); //继续等待 } //首先读取4个字节的整数 _PacketDataSize = BitConverter.ToInt32(CmdHeaderBuffer, 0); //再读取2个字节的指令 _PacketCmdID = BitConverter.ToInt32(CmdHeaderBuffer, 4); if (_PacketDataSize <= 0 || _PacketDataSize >= RECV_MAX_SIZE) { //throw new Exception(string.Format("接收到的非法数据长度的tcp命令, Cmd={0}, Length={1} , 需要立即和服务器端断开!", (TCPGameServerCmds)_PacketCmdID, _PacketDataSize)); //LogManager.WriteLog(LogTypes.Error, string.Format("接收到的非法数据长度的tcp命令, Cmd={0}, Length={1}, offset={2}, count={3}", (TCPGameServerCmds)_PacketCmdID, _PacketDataSize, offset, count)); return(false); } //增加偏移 offset += copyLeftSize; //减少拷贝量 count -= copyLeftSize; //等待数据中... IsWaitingData = true; //接收的字节归0 PacketDataHaveSize = 0; _PacketDataSize -= 8; //减去命令的长度 //接收数据(递归实现, 简单) return(WriteData(buffer, offset, count)); } } }
private UserCreateManager() { TCPHandleMsgManager.AddMsgDelegate((int)MSGCMDS.CMD_CREATE, TCPHandleMsgDelegate); }