using System.Net.Sockets; using NetCore; using NetCore.ContentParse; using NetCore.Protocol; namespace NetServer.NetLink.TCP; public class TCPServerConnection : IContentReceiver, IConnection where T : IContentParse where K : IProtocol { // public long index; public bool isConnected { get; set; } private byte[] buffData = new byte[6553]; private Socket socket; //记录半包数据 private bool isBufferData; private byte[] lastBuffData; private int lastCount; private short lastSendType; //数据结束 //尾包 byte[] weiBaoBuffData; private Thread _udpClientThread; private TCPServer _tcpServer; public long ConnectionId { get; set; } public IContentParse iContentParse { get { return _iContentParse; } } public IProtocol iProtocol { get { return _iProtocol; } } private IContentParse _iContentParse; public IProtocol _iProtocol; public long HeartbeatLasetTime; public TCPServerConnection(TCPServer tcpServer, Socket socket) { this.socket = socket; socket.NoDelay = true; _tcpServer = tcpServer; isConnected = true; _iContentParse = Activator.CreateInstance(); _iProtocol = Activator.CreateInstance(); _udpClientThread = new Thread(TheUpdate); _udpClientThread.Start(); HeartbeatLasetTime = DateTime.Now.Ticks; } private void TheUpdate() { while (socket != null) { try { int count = socket.Receive(buffData); if (count <= 0) { Thread.Sleep(1); return; } byte[] data = new byte[count]; Array.Copy(buffData, 0, data, 0, count); _iContentParse.ParseByte(data, _iProtocol, this); // LogTool.Log("数据来了" + count); } catch (Exception e) { Console.WriteLine(e); isConnected = false; break; } } Console.WriteLine("服务器执行完毕"); _tcpServer.RemoveConnection(this); } public void AddContent(byte[] data) { if (data == null) { return; } if (data.Length == 1 && data[0] == 1) { // 心跳 HeartbeatLasetTime = DateTime.Now.Ticks; return; } object serializeData = iProtocol.Deserialize(data); _tcpServer.LogicalParsing.Logic(serializeData, this); } public void SendData(object sendData) { byte[] data = iProtocol.Serialize(sendData); if (data == null) { return; } byte[] parseData = _iContentParse.AssembleByte(data); socket.SendAsync(parseData, SocketFlags.None); } public void Dispose() { socket?.Close(); socket?.Dispose(); socket = null; _tcpServer = null; _udpClientThread = null; lastBuffData = null; weiBaoBuffData = null; buffData = null; } }