private void SetReqHeader(TcpRequestBase req) { if (!req.Id.Equals(0xffffffff)) { return; } req.Id = Interlocked.Add(ref reqId, 1); req.SetIndex(0); req.WriteInt32(flagHeader); req.WriteInt64(req.Id); req.SetIndex(20);//跳过包长度 req.WriteInt32(req.ClientId); req.WriteInt32(req.ProtocolId); req.TimeTick = System.DateTime.Now.Ticks; req.WriteInt64(req.TimeTick); string md5 = MD5Code.GetMD5HashFromByte(req.getMemData()); byte[] checkData = Encoding.UTF8.GetBytes(md5); req.SetIndex(36); req.SetMd5Header(checkData); req.SetIndex(12); req.Count += 8;//加上自己 req.WriteInt64(req.Count); }
private void TcpMessage() { byte[] buffer = new byte[0x800]; List <TcpRequestBase> list = new List <TcpRequestBase>(); TcpResponseBase reponse = null; while (true) { Thread.Sleep(1); switch (status) { case 1: break; case 2: continue; default: goto StopServer; } List <TcpRequestBase> tmplist = GetSendData(); if (tmplist == null) { continue; } list.AddRange(tmplist); lock (mainLock) { switch (status) { case 1: break; case 2: DestorySendQueue(list); continue; default: DestorySendQueue(list); goto StopServer; } /*发送消息*/ for (int i = 0; i < list.Count; i++) { try { TcpRequestBase req = list[i]; if (this.client.Connected && this.stream.CanWrite) { stream.Write(req.getMemData(), 0, (int)req.Count);//udpBug,后期修复 } } catch (Exception e) { LogAgent.LogError("Tcp消息发送失败\t" + e.ToString()); } } DestorySendQueue(list); try { /*接收消息*/ if (this.client.Connected && this.client.Available > 0 && this.stream.CanRead) { int count = stream.Read(buffer, 0, buffer.Length);//默认每次只接收一个包 byte[] data = CheckPack(buffer, count); if (data == null) { continue; } reponse = GetReponsePackage(data); } } catch (Exception e) { LogAgent.LogError("Tcp消息接收失败\t" + e.ToString()); } } AddReqPackage(reponse); } StopServer: Interlocked.Add(ref status, 1); LogAgent.Log("!关闭Udp循环线程"); }