12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- using System.Net;
- using System.Net.Sockets;
- using NetCore;
- using NetCore.ContentParse;
- using NetCore.Protocol;
- namespace NetClientCore.TCP;
- public class TCPClient<T, K> : 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<T>();
- _iProtocol = Activator.CreateInstance<K>();
- _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);
- }
- }
|