AsyncSocketServer.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Sockets;
  8. using System.Security.Authentication;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using SuperSocket.Common;
  13. using SuperSocket.SocketBase;
  14. using SuperSocket.SocketBase.Command;
  15. using SuperSocket.SocketBase.Protocol;
  16. using SuperSocket.SocketEngine.AsyncSocket;
  17. namespace SuperSocket.SocketEngine
  18. {
  19. class AsyncSocketServer : TcpSocketServerBase, IActiveConnector
  20. {
  21. public AsyncSocketServer(IAppServer appServer, ListenerInfo[] listeners)
  22. : base(appServer, listeners)
  23. {
  24. }
  25. private BufferManager m_BufferManager;
  26. private ConcurrentStack<SocketAsyncEventArgsProxy> m_ReadWritePool;
  27. public override bool Start()
  28. {
  29. try
  30. {
  31. int bufferSize = AppServer.Config.ReceiveBufferSize;
  32. if (bufferSize <= 0)
  33. bufferSize = 1024 * 4;
  34. m_BufferManager = new BufferManager(bufferSize * AppServer.Config.MaxConnectionNumber, bufferSize);
  35. try
  36. {
  37. m_BufferManager.InitBuffer();
  38. }
  39. catch (Exception e)
  40. {
  41. AppServer.Logger.Error("Failed to allocate buffer for async socket communication, may because there is no enough memory, please decrease maxConnectionNumber in configuration!", e);
  42. return false;
  43. }
  44. // preallocate pool of SocketAsyncEventArgs objects
  45. SocketAsyncEventArgs socketEventArg;
  46. var socketArgsProxyList = new List<SocketAsyncEventArgsProxy>(AppServer.Config.MaxConnectionNumber);
  47. for (int i = 0; i < AppServer.Config.MaxConnectionNumber; i++)
  48. {
  49. //Pre-allocate a set of reusable SocketAsyncEventArgs
  50. socketEventArg = new SocketAsyncEventArgs();
  51. m_BufferManager.SetBuffer(socketEventArg);
  52. socketArgsProxyList.Add(new SocketAsyncEventArgsProxy(socketEventArg));
  53. }
  54. m_ReadWritePool = new ConcurrentStack<SocketAsyncEventArgsProxy>(socketArgsProxyList);
  55. if (!base.Start())
  56. return false;
  57. IsRunning = true;
  58. return true;
  59. }
  60. catch (Exception e)
  61. {
  62. AppServer.Logger.Error(e);
  63. return false;
  64. }
  65. }
  66. protected override void OnNewClientAccepted(ISocketListener listener, Socket client, object state)
  67. {
  68. if (IsStopped)
  69. return;
  70. ProcessNewClient(client, listener.Info.Security);
  71. }
  72. private IAppSession ProcessNewClient(Socket client, SslProtocols security)
  73. {
  74. //Get the socket for the accepted client connection and put it into the
  75. //ReadEventArg object user token
  76. SocketAsyncEventArgsProxy socketEventArgsProxy;
  77. if (!m_ReadWritePool.TryPop(out socketEventArgsProxy))
  78. {
  79. AppServer.AsyncRun(client.SafeClose);
  80. if (AppServer.Logger.IsErrorEnabled)
  81. AppServer.Logger.ErrorFormat("Max connection number {0} was reached!", AppServer.Config.MaxConnectionNumber);
  82. return null;
  83. }
  84. ISocketSession socketSession;
  85. if (security == SslProtocols.None)
  86. socketSession = new AsyncSocketSession(client, socketEventArgsProxy);
  87. else
  88. socketSession = new AsyncStreamSocketSession(client, security, socketEventArgsProxy);
  89. var session = CreateSession(client, socketSession);
  90. if (session == null)
  91. {
  92. socketEventArgsProxy.Reset();
  93. this.m_ReadWritePool.Push(socketEventArgsProxy);
  94. AppServer.AsyncRun(client.SafeClose);
  95. return null;
  96. }
  97. socketSession.Closed += SessionClosed;
  98. var negotiateSession = socketSession as INegotiateSocketSession;
  99. if (negotiateSession == null)
  100. {
  101. if (RegisterSession(session))
  102. {
  103. AppServer.AsyncRun(() => socketSession.Start());
  104. }
  105. return session;
  106. }
  107. negotiateSession.NegotiateCompleted += OnSocketSessionNegotiateCompleted;
  108. negotiateSession.Negotiate();
  109. return null;
  110. }
  111. private void OnSocketSessionNegotiateCompleted(object sender, EventArgs e)
  112. {
  113. var socketSession = sender as ISocketSession;
  114. var negotiateSession = socketSession as INegotiateSocketSession;
  115. if (!negotiateSession.Result)
  116. {
  117. socketSession.Close(CloseReason.SocketError);
  118. return;
  119. }
  120. if (RegisterSession(negotiateSession.AppSession))
  121. {
  122. AppServer.AsyncRun(() => socketSession.Start());
  123. }
  124. }
  125. private bool RegisterSession(IAppSession appSession)
  126. {
  127. if (AppServer.RegisterSession(appSession))
  128. return true;
  129. appSession.SocketSession.Close(CloseReason.InternalError);
  130. return false;
  131. }
  132. public override void ResetSessionSecurity(IAppSession session, SslProtocols security)
  133. {
  134. ISocketSession socketSession;
  135. var socketAsyncProxy = ((IAsyncSocketSessionBase)session.SocketSession).SocketAsyncProxy;
  136. if (security == SslProtocols.None)
  137. socketSession = new AsyncSocketSession(session.SocketSession.Client, socketAsyncProxy, true);
  138. else
  139. socketSession = new AsyncStreamSocketSession(session.SocketSession.Client, security, socketAsyncProxy, true);
  140. socketSession.Initialize(session);
  141. socketSession.Start();
  142. }
  143. void SessionClosed(ISocketSession session, CloseReason reason)
  144. {
  145. var socketSession = session as IAsyncSocketSessionBase;
  146. if (socketSession == null)
  147. return;
  148. var proxy = socketSession.SocketAsyncProxy;
  149. proxy.Reset();
  150. var args = proxy.SocketEventArgs;
  151. var serverState = AppServer.State;
  152. var pool = this.m_ReadWritePool;
  153. if (pool == null || serverState == ServerState.Stopping || serverState == ServerState.NotStarted)
  154. {
  155. if(!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload())
  156. args.Dispose();
  157. return;
  158. }
  159. if (proxy.OrigOffset != args.Offset)
  160. {
  161. args.SetBuffer(proxy.OrigOffset, AppServer.Config.ReceiveBufferSize);
  162. }
  163. if (!proxy.IsRecyclable)
  164. {
  165. //cannot be recycled, so release the resource and don't return it to the pool
  166. args.Dispose();
  167. return;
  168. }
  169. pool.Push(proxy);
  170. }
  171. public override void Stop()
  172. {
  173. if (IsStopped)
  174. return;
  175. lock (SyncRoot)
  176. {
  177. if (IsStopped)
  178. return;
  179. base.Stop();
  180. foreach (var item in m_ReadWritePool)
  181. item.SocketEventArgs.Dispose();
  182. m_ReadWritePool = null;
  183. m_BufferManager = null;
  184. IsRunning = false;
  185. }
  186. }
  187. class ActiveConnectState
  188. {
  189. public TaskCompletionSource<ActiveConnectResult> TaskSource { get; private set; }
  190. public Socket Socket { get; private set; }
  191. public ActiveConnectState(TaskCompletionSource<ActiveConnectResult> taskSource, Socket socket)
  192. {
  193. TaskSource = taskSource;
  194. Socket = socket;
  195. }
  196. }
  197. Task<ActiveConnectResult> IActiveConnector.ActiveConnect(EndPoint targetEndPoint)
  198. {
  199. return ((IActiveConnector)this).ActiveConnect(targetEndPoint, null);
  200. }
  201. Task<ActiveConnectResult> IActiveConnector.ActiveConnect(EndPoint targetEndPoint, EndPoint localEndPoint)
  202. {
  203. var taskSource = new TaskCompletionSource<ActiveConnectResult>();
  204. var socket = new Socket(targetEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  205. if (localEndPoint != null)
  206. {
  207. socket.ExclusiveAddressUse = false;
  208. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  209. socket.Bind(localEndPoint);
  210. }
  211. socket.BeginConnect(targetEndPoint, OnActiveConnectCallback, new ActiveConnectState(taskSource, socket));
  212. return taskSource.Task;
  213. }
  214. private void OnActiveConnectCallback(IAsyncResult result)
  215. {
  216. var connectState = result.AsyncState as ActiveConnectState;
  217. try
  218. {
  219. var socket = connectState.Socket;
  220. socket.EndConnect(result);
  221. var session = ProcessNewClient(socket, SslProtocols.None);
  222. if (session == null)
  223. connectState.TaskSource.SetException(new Exception("Failed to create session for this socket."));
  224. else
  225. connectState.TaskSource.SetResult(new ActiveConnectResult { Result = true, Session = session });
  226. }
  227. catch (Exception e)
  228. {
  229. connectState.TaskSource.SetException(e);
  230. }
  231. }
  232. }
  233. }