using System; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Fort23.UTool; using NetCore; using NetCore.ContentParse; using NetCore.Protocol; namespace NetClientCore.TCP { public class TCPClient : IContentReceiver, IConnection where T : IContentParse where K : IProtocol { private Socket socket; public long ConnectionId { get; set; } private byte[] buffData = new byte[655300]; public bool isConnected { get; set; } public IContentParse iContentParse { get { return _iContentParse; } } public IProtocol iProtocol { get { return _iProtocol; } } private IContentParse _iContentParse; public IProtocol _iProtocol; private Thread _udpClientThread; private Thread _heartbeat; private ILogicalParsing LogicalParsing; public async Task Connect(string ip, int port, ILogicalParsing LogicalParsing) { this.LogicalParsing = LogicalParsing; socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); await socket.ConnectAsync(ip, port); _iContentParse = Activator.CreateInstance(); _iProtocol = Activator.CreateInstance(); _udpClientThread = new Thread(TheUpdate); _udpClientThread.Start(); _heartbeat = new Thread(HeartbeatUpdate); _heartbeat.Start(); } private void HeartbeatUpdate() { while (socket != null) { SendHeartbeat(); Thread.Sleep(10000); } } 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) { LogTool.Error(e); isConnected = false; break; } } LogTool.Log("服务器执行完毕"); } public void AddContent(byte[] data) { if (data == null) { return; } if (data.Length == 1 && data[0] == 1) { // 心跳 return; } object serializeData = iProtocol.Deserialize(data); LogicalParsing.Logic(serializeData, this); } public void SendData(object sendData) { byte[] data = iProtocol.Serialize(sendData); byte[] parseData = _iContentParse.AssembleByte(data); socket.SendAsync(parseData, SocketFlags.None); } /// /// 发送心跳 /// private void SendHeartbeat() { byte[] bytes = new byte[] { 1 }; byte[] parseData = _iContentParse.AssembleByte(bytes); socket.SendAsync(parseData, SocketFlags.None); } public void Dispose() { socket?.Dispose(); socket?.Close(); socket = null; _iContentParse = null; _iProtocol = null; _udpClientThread = null; _heartbeat = null; LogicalParsing = null; } } }