TcppClient.cs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. using Azylee.Core.ThreadUtils.SleepUtils;
  2. using Azylee.Core.WindowsUtils.ConsoleUtils;
  3. using Azylee.Jsons;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Net.Sockets;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace Azylee.YeahWeb.SocketUtils.TcpUtils
  11. {
  12. public class TcppClient
  13. {
  14. const int ReceiveBufferSize = 1024;
  15. private string _IP = "";
  16. private int _Port = 52801;
  17. private TcpClient Client = null;
  18. private NetworkStream networkStream = null;
  19. TcpDelegate.ReceiveMessage ReceiveMessage;
  20. TcpDelegate.OnConnect OnConnect;
  21. TcpDelegate.OnDisconnect OnDisconnect;
  22. //public TcpDataConverter.Message ReceiveMessage;
  23. /// <summary>
  24. /// 构造函数
  25. /// </summary>
  26. /// <param name="ip"></param>
  27. /// <param name="port"></param>
  28. public TcppClient(string ip, int port,
  29. TcpDelegate.ReceiveMessage receive,
  30. TcpDelegate.OnConnect connect,
  31. TcpDelegate.OnDisconnect disconnect)
  32. {
  33. this._IP = ip;
  34. this._Port = port;
  35. ReceiveMessage += receive;
  36. OnConnect += connect;
  37. OnDisconnect += disconnect;
  38. }
  39. #region 连接和关闭连接
  40. /// <summary>
  41. /// 连接到TcpServer(重连)
  42. /// </summary>
  43. public bool Connect()
  44. {
  45. try
  46. {
  47. if (this.Client == null || !this.Client.Connected)
  48. {
  49. this.Client = new TcpClient();
  50. //this.Read();
  51. IAsyncResult ar = this.Client.BeginConnect(this._IP, this._Port, acceptCallback, this.Client);
  52. bool isConnect = ar.AsyncWaitHandle.WaitOne(1000);
  53. if (isConnect) return true;
  54. }
  55. }
  56. catch { }
  57. return false;
  58. }
  59. /// <summary>
  60. /// 关闭连接
  61. /// </summary>
  62. public void Disconnect()
  63. {
  64. networkStream?.Close();
  65. Client?.Close();
  66. }
  67. #endregion
  68. #region 连接后的读写操作
  69. /// <summary>
  70. /// 发送数据
  71. /// </summary>
  72. /// <param name="model">数据模型</param>
  73. public bool Write(TcpDataModel model)
  74. {
  75. bool flag = false;
  76. if (this.Client != null && this.Client.Connected)
  77. {
  78. flag = TcpStreamHelper.Write(Client, model);
  79. }
  80. return flag;
  81. }
  82. /// <summary>
  83. /// 发送数据
  84. /// </summary>
  85. /// <param name="type">类型</param>
  86. /// <param name="data">数据</param>
  87. public bool Write(int type, byte[] data)
  88. {
  89. return Write(new TcpDataModel() { Type = type, Data = data });
  90. }
  91. /// <summary>
  92. /// 发送数据
  93. /// </summary>
  94. /// <param name="type">类型</param>
  95. /// <param name="s">字符串</param>
  96. public bool Write(int type, string s)
  97. {
  98. return Write(new TcpDataModel() { Type = type, Data = Json.Object2Byte(s) });
  99. }
  100. /// <summary>
  101. /// 接受数据
  102. /// </summary>
  103. private void acceptCallback(IAsyncResult state)
  104. {
  105. try
  106. {
  107. this.Client = (TcpClient)state.AsyncState;
  108. this.Client.EndConnect(state);
  109. string host = this.Client.Client.RemoteEndPoint.ToString();
  110. ConnectTask(host, this.Client);
  111. }
  112. catch { }
  113. }
  114. private void ConnectTask(string host, TcpClient client)
  115. {
  116. Task.Factory.StartNew(() =>
  117. {
  118. OnConnect?.Invoke(host);//委托:已连接
  119. while (client.Connected)
  120. {
  121. try
  122. {
  123. TcpDataModel model = TcpStreamHelper.Read(client);
  124. if (model != null)
  125. {
  126. if (model.Type == int.MaxValue)
  127. {
  128. //返回心跳
  129. Write(new TcpDataModel() { Type = int.MaxValue });
  130. }
  131. else
  132. {
  133. ReceiveMessage(host, model);//委托:接收消息
  134. }
  135. }
  136. }
  137. catch { }
  138. //Sleep.S(1);
  139. }
  140. client.Close();
  141. OnDisconnect?.Invoke(host);//委托:断开连接
  142. });
  143. //lstn.BeginAcceptTcpClient(new AsyncCallback(acceptCallback), lstn);
  144. }
  145. #endregion
  146. }
  147. }