TSocket.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Threading.Tasks;
  5. namespace Base
  6. {
  7. /// <summary>
  8. /// 封装Socket,将回调push到主线程处理
  9. /// </summary>
  10. public sealed class TSocket: IDisposable
  11. {
  12. private readonly TPoller poller;
  13. private Socket socket;
  14. private readonly SocketAsyncEventArgs innArgs = new SocketAsyncEventArgs();
  15. private readonly SocketAsyncEventArgs outArgs = new SocketAsyncEventArgs();
  16. public Action<SocketError> OnConn;
  17. public Action<int, SocketError> OnRecv;
  18. public Action<int, SocketError> OnSend;
  19. public Action<SocketError> OnDisconnect;
  20. public TSocket(TPoller poller)
  21. {
  22. this.poller = poller;
  23. this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  24. this.innArgs.Completed += this.OnComplete;
  25. this.outArgs.Completed += this.OnComplete;
  26. }
  27. public TSocket(TPoller poller, string host, int port): this(poller)
  28. {
  29. try
  30. {
  31. this.Bind(host, port);
  32. this.Listen(100);
  33. }
  34. catch (Exception e)
  35. {
  36. throw new Exception($"socket bind error: {host} {port}", e);
  37. }
  38. }
  39. public Socket Socket
  40. {
  41. get
  42. {
  43. return this.socket;
  44. }
  45. }
  46. public string RemoteAddress
  47. {
  48. get
  49. {
  50. IPEndPoint ipEndPoint = (IPEndPoint)this.socket.RemoteEndPoint;
  51. return ipEndPoint.Address + ":" + ipEndPoint.Port;
  52. }
  53. }
  54. public void Dispose()
  55. {
  56. if (this.socket == null)
  57. {
  58. return;
  59. }
  60. this.socket.Close();
  61. this.innArgs.Dispose();
  62. this.outArgs.Dispose();
  63. this.socket = null;
  64. }
  65. private void Bind(string host, int port)
  66. {
  67. this.socket.Bind(new IPEndPoint(IPAddress.Parse(host), port));
  68. }
  69. private void Listen(int backlog)
  70. {
  71. this.socket.Listen(backlog);
  72. }
  73. public Task<bool> AcceptAsync(TSocket accpetSocket)
  74. {
  75. if (this.socket == null)
  76. {
  77. throw new Exception($"TSocket已经被Dispose,不能接收连接!");
  78. }
  79. var tcs = new TaskCompletionSource<bool>();
  80. this.innArgs.UserToken = tcs;
  81. this.innArgs.AcceptSocket = accpetSocket.socket;
  82. if (!this.socket.AcceptAsync(this.innArgs))
  83. {
  84. OnAcceptComplete(this.innArgs);
  85. }
  86. return tcs.Task;
  87. }
  88. private void OnAcceptComplete(SocketAsyncEventArgs e)
  89. {
  90. if (this.socket == null)
  91. {
  92. return;
  93. }
  94. var tcs = (TaskCompletionSource<bool>)e.UserToken;
  95. e.UserToken = null;
  96. if (e.SocketError != SocketError.Success)
  97. {
  98. tcs.SetException(new Exception($"socket error: {e.SocketError}"));
  99. return;
  100. }
  101. tcs.SetResult(true);
  102. }
  103. private void OnComplete(object sender, SocketAsyncEventArgs e)
  104. {
  105. Action action;
  106. switch (e.LastOperation)
  107. {
  108. case SocketAsyncOperation.Connect:
  109. action = () => OnConnectComplete(e);
  110. break;
  111. case SocketAsyncOperation.Receive:
  112. action = () => OnRecvComplete(e);
  113. break;
  114. case SocketAsyncOperation.Send:
  115. action = () => OnSendComplete(e);
  116. break;
  117. case SocketAsyncOperation.Disconnect:
  118. action = () => OnDisconnectComplete(e);
  119. break;
  120. case SocketAsyncOperation.Accept:
  121. action = () => OnAcceptComplete(e);
  122. break;
  123. default:
  124. throw new Exception($"socket error: {e.LastOperation}");
  125. }
  126. // 回调到主线程处理
  127. this.poller.Add(action);
  128. }
  129. public bool ConnectAsync(string host, int port)
  130. {
  131. this.outArgs.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(host), port);
  132. if (this.socket.ConnectAsync(this.outArgs))
  133. {
  134. return true;
  135. }
  136. OnConnectComplete(this.outArgs);
  137. return false;
  138. }
  139. private void OnConnectComplete(SocketAsyncEventArgs e)
  140. {
  141. if (this.socket == null)
  142. {
  143. return;
  144. }
  145. if (this.OnConn == null)
  146. {
  147. return;
  148. }
  149. this.OnConn(e.SocketError);
  150. }
  151. public bool RecvAsync(byte[] buffer, int offset, int count)
  152. {
  153. try
  154. {
  155. this.innArgs.SetBuffer(buffer, offset, count);
  156. }
  157. catch (Exception e)
  158. {
  159. throw new Exception($"socket set buffer error: {buffer.Length}, {offset}, {count}", e);
  160. }
  161. if (this.socket.ReceiveAsync(this.innArgs))
  162. {
  163. return true;
  164. }
  165. OnRecvComplete(this.innArgs);
  166. return false;
  167. }
  168. private void OnRecvComplete(SocketAsyncEventArgs e)
  169. {
  170. if (this.socket == null)
  171. {
  172. return;
  173. }
  174. if (this.OnRecv == null)
  175. {
  176. return;
  177. }
  178. this.OnRecv(e.BytesTransferred, e.SocketError);
  179. }
  180. public bool SendAsync(byte[] buffer, int offset, int count)
  181. {
  182. try
  183. {
  184. this.outArgs.SetBuffer(buffer, offset, count);
  185. }
  186. catch (Exception e)
  187. {
  188. throw new Exception($"socket set buffer error: {buffer.Length}, {offset}, {count}", e);
  189. }
  190. if (this.socket.SendAsync(this.outArgs))
  191. {
  192. return true;
  193. }
  194. OnSendComplete(this.outArgs);
  195. return false;
  196. }
  197. private void OnSendComplete(SocketAsyncEventArgs e)
  198. {
  199. if (this.socket == null)
  200. {
  201. return;
  202. }
  203. if (this.OnSend == null)
  204. {
  205. return;
  206. }
  207. this.OnSend(e.BytesTransferred, e.SocketError);
  208. }
  209. private void OnDisconnectComplete(SocketAsyncEventArgs e)
  210. {
  211. if (this.socket == null)
  212. {
  213. return;
  214. }
  215. if (this.OnDisconnect == null)
  216. {
  217. return;
  218. }
  219. this.OnDisconnect(e.SocketError);
  220. }
  221. }
  222. }