AsyncSocketSession.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net.Sockets;
  7. using System.Text;
  8. using System.Threading;
  9. using SuperSocket.Common;
  10. using SuperSocket.SocketBase;
  11. using SuperSocket.SocketBase.Command;
  12. using SuperSocket.SocketBase.Logging;
  13. using SuperSocket.SocketBase.Protocol;
  14. using SuperSocket.SocketEngine.AsyncSocket;
  15. namespace SuperSocket.SocketEngine
  16. {
  17. class AsyncSocketSession : SocketSession, IAsyncSocketSession
  18. {
  19. private bool m_IsReset;
  20. private SocketAsyncEventArgs m_SocketEventArgSend;
  21. public AsyncSocketSession(Socket client, SocketAsyncEventArgsProxy socketAsyncProxy)
  22. : this(client, socketAsyncProxy, false)
  23. {
  24. }
  25. public AsyncSocketSession(Socket client, SocketAsyncEventArgsProxy socketAsyncProxy, bool isReset)
  26. : base(client)
  27. {
  28. SocketAsyncProxy = socketAsyncProxy;
  29. m_IsReset = isReset;
  30. }
  31. ILog ILoggerProvider.Logger
  32. {
  33. get { return AppSession.Logger; }
  34. }
  35. public override void Initialize(IAppSession appSession)
  36. {
  37. base.Initialize(appSession);
  38. //Initialize SocketAsyncProxy for receiving
  39. SocketAsyncProxy.Initialize(this);
  40. if (!SyncSend)
  41. {
  42. //Initialize SocketAsyncEventArgs for sending
  43. m_SocketEventArgSend = new SocketAsyncEventArgs();
  44. m_SocketEventArgSend.Completed += new EventHandler<SocketAsyncEventArgs>(OnSendingCompleted);
  45. }
  46. }
  47. public override void Start()
  48. {
  49. StartReceive(SocketAsyncProxy.SocketEventArgs);
  50. if (!m_IsReset)
  51. StartSession();
  52. }
  53. bool ProcessCompleted(SocketAsyncEventArgs e)
  54. {
  55. if (e.SocketError == SocketError.Success)
  56. {
  57. if (e.BytesTransferred > 0)
  58. {
  59. return true;
  60. }
  61. }
  62. else
  63. {
  64. LogError((int)e.SocketError);
  65. }
  66. return false;
  67. }
  68. void OnSendingCompleted(object sender, SocketAsyncEventArgs e)
  69. {
  70. var queue = e.UserToken as SendingQueue;
  71. if (!ProcessCompleted(e))
  72. {
  73. ClearPrevSendState(e);
  74. OnSendError(queue, CloseReason.SocketError);
  75. return;
  76. }
  77. var count = queue.Sum(q => q.Count);
  78. if (count != e.BytesTransferred)
  79. {
  80. queue.InternalTrim(e.BytesTransferred);
  81. AppSession.Logger.InfoFormat("{0} of {1} were transferred, send the rest {2} bytes right now.", e.BytesTransferred, count, queue.Sum(q => q.Count));
  82. ClearPrevSendState(e);
  83. SendAsync(queue);
  84. return;
  85. }
  86. ClearPrevSendState(e);
  87. base.OnSendingCompleted(queue);
  88. }
  89. private void ClearPrevSendState(SocketAsyncEventArgs e)
  90. {
  91. e.UserToken = null;
  92. //Clear previous sending buffer of sae to avoid memory leak
  93. if (e.Buffer != null)
  94. {
  95. e.SetBuffer(null, 0, 0);
  96. }
  97. else if (e.BufferList != null)
  98. {
  99. e.BufferList = null;
  100. }
  101. }
  102. private void StartReceive(SocketAsyncEventArgs e)
  103. {
  104. StartReceive(e, 0);
  105. }
  106. private void StartReceive(SocketAsyncEventArgs e, int offsetDelta)
  107. {
  108. bool willRaiseEvent = false;
  109. try
  110. {
  111. if (offsetDelta < 0 || offsetDelta >= Config.ReceiveBufferSize)
  112. throw new ArgumentException(string.Format("Illigal offsetDelta: {0}", offsetDelta), "offsetDelta");
  113. var predictOffset = SocketAsyncProxy.OrigOffset + offsetDelta;
  114. if (e.Offset != predictOffset)
  115. {
  116. e.SetBuffer(predictOffset, Config.ReceiveBufferSize - offsetDelta);
  117. }
  118. // the connection is closing or closed
  119. if (!OnReceiveStarted())
  120. return;
  121. willRaiseEvent = Client.ReceiveAsync(e);
  122. }
  123. catch (Exception exc)
  124. {
  125. LogError(exc);
  126. OnReceiveTerminated(CloseReason.SocketError);
  127. return;
  128. }
  129. if (!willRaiseEvent)
  130. {
  131. ProcessReceive(e);
  132. }
  133. }
  134. protected override void SendSync(SendingQueue queue)
  135. {
  136. try
  137. {
  138. for (var i = 0; i < queue.Count; i++)
  139. {
  140. var item = queue[i];
  141. var client = Client;
  142. if (client == null)
  143. return;
  144. client.Send(item.Array, item.Offset, item.Count, SocketFlags.None);
  145. }
  146. OnSendingCompleted(queue);
  147. }
  148. catch (Exception e)
  149. {
  150. LogError(e);
  151. OnSendError(queue, CloseReason.SocketError);
  152. return;
  153. }
  154. }
  155. protected override void SendAsync(SendingQueue queue)
  156. {
  157. try
  158. {
  159. m_SocketEventArgSend.UserToken = queue;
  160. if (queue.Count > 1)
  161. m_SocketEventArgSend.BufferList = queue;
  162. else
  163. {
  164. var item = queue[0];
  165. m_SocketEventArgSend.SetBuffer(item.Array, item.Offset, item.Count);
  166. }
  167. var client = Client;
  168. if (client == null)
  169. {
  170. OnSendError(queue, CloseReason.SocketError);
  171. return;
  172. }
  173. if (!client.SendAsync(m_SocketEventArgSend))
  174. OnSendingCompleted(client, m_SocketEventArgSend);
  175. }
  176. catch (Exception e)
  177. {
  178. LogError(e);
  179. ClearPrevSendState(m_SocketEventArgSend);
  180. OnSendError(queue, CloseReason.SocketError);
  181. }
  182. }
  183. public SocketAsyncEventArgsProxy SocketAsyncProxy { get; private set; }
  184. public void ProcessReceive(SocketAsyncEventArgs e)
  185. {
  186. if (!ProcessCompleted(e))
  187. {
  188. OnReceiveTerminated(e.SocketError == SocketError.Success ? CloseReason.ClientClosing : CloseReason.SocketError);
  189. return;
  190. }
  191. OnReceiveEnded();
  192. int offsetDelta;
  193. try
  194. {
  195. offsetDelta = this.AppSession.ProcessRequest(e.Buffer, e.Offset, e.BytesTransferred, true);
  196. }
  197. catch (Exception exc)
  198. {
  199. LogError("Protocol error", exc);
  200. this.Close(CloseReason.ProtocolError);
  201. return;
  202. }
  203. //read the next block of data sent from the client
  204. StartReceive(e, offsetDelta);
  205. }
  206. protected override void OnClosed(CloseReason reason)
  207. {
  208. var sae = m_SocketEventArgSend;
  209. if (sae == null)
  210. {
  211. base.OnClosed(reason);
  212. return;
  213. }
  214. if (Interlocked.CompareExchange(ref m_SocketEventArgSend, null, sae) == sae)
  215. {
  216. sae.Dispose();
  217. base.OnClosed(reason);
  218. }
  219. }
  220. public override void ApplySecureProtocol()
  221. {
  222. //TODO: Implement async socket SSL/TLS encryption
  223. }
  224. public override int OrigReceiveOffset
  225. {
  226. get { return SocketAsyncProxy.OrigOffset; }
  227. }
  228. }
  229. }