TCPClient.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System.Net;
  2. using System.Net.Sockets;
  3. using NetCore;
  4. using NetCore.ContentParse;
  5. using NetCore.Protocol;
  6. namespace NetClientCore.TCP;
  7. public class TCPClient<T, K> : IContentReceiver, IConnection
  8. where T : IContentParse where K : IProtocol
  9. {
  10. private Socket socket;
  11. private byte[] buffData = new byte[655300];
  12. public bool isConnected { get; set; }
  13. public IContentParse iContentParse
  14. {
  15. get { return _iContentParse; }
  16. }
  17. public IProtocol iProtocol
  18. {
  19. get { return _iProtocol; }
  20. }
  21. private IContentParse _iContentParse;
  22. public IProtocol _iProtocol;
  23. private Thread _udpClientThread;
  24. private ILogicalParsing LogicalParsing;
  25. public async Task Connect(string ip, int port, ILogicalParsing LogicalParsing)
  26. {
  27. this.LogicalParsing = LogicalParsing;
  28. socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  29. await socket.ConnectAsync(ip, port);
  30. _iContentParse = Activator.CreateInstance<T>();
  31. _iProtocol = Activator.CreateInstance<K>();
  32. _udpClientThread = new Thread(TheUpdate);
  33. _udpClientThread.Start();
  34. }
  35. private void TheUpdate()
  36. {
  37. while (socket != null)
  38. {
  39. try
  40. {
  41. int count = socket.Receive(buffData);
  42. if (count <= 0)
  43. {
  44. Thread.Sleep(1);
  45. return;
  46. }
  47. byte[] data = new byte[count];
  48. Array.Copy(buffData, 0, data, 0, count);
  49. _iContentParse.ParseByte(data, _iProtocol, this);
  50. // LogTool.Log("数据来了" + count);
  51. }
  52. catch (Exception e)
  53. {
  54. Console.WriteLine(e);
  55. isConnected = false;
  56. break;
  57. }
  58. }
  59. Console.WriteLine("服务器执行完毕");
  60. }
  61. public void AddContent(object data)
  62. {
  63. LogicalParsing.Logic(data, this);
  64. }
  65. public void SendData(object sendData)
  66. {
  67. byte[] data = iProtocol.Serialize(sendData);
  68. byte[] parseData= _iContentParse.AssembleByte(data);
  69. socket.SendAsync(parseData, SocketFlags.None);
  70. }
  71. }