using System.Net; using System.Net.Sockets; 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; 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 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(); } 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("服务器执行完毕"); } public void AddContent(object data) { LogicalParsing.Logic(data, this); } public void SendData(object sendData) { byte[] data = iProtocol.Serialize(sendData); byte[] parseData= _iContentParse.AssembleByte(data); socket.SendAsync(parseData, SocketFlags.None); } }