SocketAsyncEventArgs.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. // System.Net.Sockets.SocketAsyncEventArgs.cs
  2. //
  3. // Authors:
  4. // Marek Habersack ([email protected])
  5. //
  6. // Copyright (c) 2008 Novell, Inc. (http://www.novell.com)
  7. //
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. #if NET_2_0
  29. using System;
  30. using System.Collections.Generic;
  31. using System.Threading;
  32. namespace System.Net.Sockets
  33. {
  34. public class SocketAsyncEventArgs : EventArgs, IDisposable
  35. {
  36. public event EventHandler<SocketAsyncEventArgs> Completed;
  37. IList <ArraySegment <byte>> _bufferList;
  38. public Socket AcceptSocket { get; set; }
  39. public byte[] Buffer { get; private set; }
  40. public IList<ArraySegment<byte>> BufferList {
  41. get { return _bufferList; }
  42. set {
  43. if (Buffer != null)
  44. throw new ArgumentException ("Buffer and BufferList properties cannot both be non-null.");
  45. _bufferList = value;
  46. }
  47. }
  48. public int BytesTransferred { get; private set; }
  49. public int Count { get; private set; }
  50. public bool DisconnectReuseSocket { get; set; }
  51. public SocketAsyncOperation LastOperation { get; private set; }
  52. public int Offset { get; private set; }
  53. public IPPacketInformation ReceiveMessageFromPacketInfo { get; private set; }
  54. public EndPoint RemoteEndPoint { get; set; }
  55. public SendPacketsElement[] SendPacketsElements { get; set; }
  56. public TransmitFileOptions SendPacketsFlags { get; set; }
  57. public int SendPacketsSendSize { get; set; }
  58. public SocketError SocketError { get; set; }
  59. public SocketFlags SocketFlags { get; set; }
  60. public object UserToken { get; set; }
  61. Socket curSocket;
  62. public SocketAsyncEventArgs ()
  63. {
  64. AcceptSocket = null;
  65. Buffer = null;
  66. BufferList = null;
  67. BytesTransferred = 0;
  68. Count = 0;
  69. DisconnectReuseSocket = false;
  70. LastOperation = SocketAsyncOperation.None;
  71. Offset = 0;
  72. RemoteEndPoint = null;
  73. SendPacketsElements = null;
  74. SendPacketsFlags = TransmitFileOptions.UseDefaultWorkerThread;
  75. SendPacketsSendSize = 0;
  76. SocketError = SocketError.Success;
  77. SocketFlags = SocketFlags.None;
  78. UserToken = null;
  79. }
  80. ~SocketAsyncEventArgs ()
  81. {
  82. Dispose (false);
  83. }
  84. void Dispose (bool disposing)
  85. {
  86. Socket acceptSocket = AcceptSocket;
  87. if (acceptSocket != null)
  88. acceptSocket.Close ();
  89. if (disposing)
  90. GC.SuppressFinalize (this);
  91. }
  92. void IDisposable.Dispose ()
  93. {
  94. Dispose (true);
  95. }
  96. protected virtual void OnCompleted (SocketAsyncEventArgs e)
  97. {
  98. if (e == null)
  99. return;
  100. if (e.Completed != null)
  101. e.Completed (e.curSocket, e);
  102. }
  103. public void SetBuffer (int offset, int count)
  104. {
  105. SetBufferInternal (Buffer, offset, count);
  106. }
  107. public void SetBuffer (byte[] buffer, int offset, int count)
  108. {
  109. SetBufferInternal (buffer, offset, count);
  110. }
  111. void SetBufferInternal (byte[] buffer, int offset, int count)
  112. {
  113. if (buffer != null) {
  114. if (BufferList != null)
  115. throw new ArgumentException ("Buffer and BufferList properties cannot both be non-null.");
  116. int buflen = buffer.Length;
  117. if (offset < 0 || offset >= buflen)
  118. throw new ArgumentOutOfRangeException ("offset");
  119. if (count < 0 || count + offset > buflen)
  120. throw new ArgumentOutOfRangeException ("count");
  121. }
  122. Count = count;
  123. Offset = offset;
  124. Buffer = buffer;
  125. }
  126. #region Internals
  127. void AcceptCallback ()
  128. {
  129. SocketError = SocketError.Success;
  130. LastOperation = SocketAsyncOperation.Accept;
  131. try {
  132. curSocket.Accept (AcceptSocket);
  133. } catch (SocketException ex) {
  134. SocketError = ex.SocketErrorCode;
  135. throw;
  136. } finally {
  137. OnCompleted (this);
  138. }
  139. }
  140. void ReceiveCallback ()
  141. {
  142. SocketError = SocketError.Success;
  143. LastOperation = SocketAsyncOperation.Receive;
  144. SocketError error = SocketError.Success;
  145. try {
  146. BytesTransferred = curSocket.Receive_nochecks (Buffer, Offset, Count, SocketFlags, out error);
  147. } finally {
  148. SocketError = error;
  149. OnCompleted (this);
  150. }
  151. }
  152. void ConnectCallback ()
  153. {
  154. SocketError = SocketError.Success;
  155. LastOperation = SocketAsyncOperation.Connect;
  156. SocketError error = SocketError.Success;
  157. try {
  158. if (!curSocket.Blocking) {
  159. int success;
  160. curSocket.Poll (-1, SelectMode.SelectWrite, out success);
  161. SocketError = (SocketError)success;
  162. if (success == 0)
  163. curSocket.Connected = true;
  164. else
  165. return;
  166. } else {
  167. curSocket.seed_endpoint = RemoteEndPoint;
  168. curSocket.Connect (RemoteEndPoint);
  169. curSocket.Connected = true;
  170. }
  171. } finally {
  172. SocketError = error;
  173. OnCompleted (this);
  174. }
  175. }
  176. void SendCallback ()
  177. {
  178. SocketError = SocketError.Success;
  179. LastOperation = SocketAsyncOperation.Send;
  180. SocketError error = SocketError.Success;
  181. try {
  182. BytesTransferred = curSocket.Send_nochecks (Buffer, Offset, Count, SocketFlags.None, out error);
  183. } finally {
  184. SocketError = error;
  185. OnCompleted (this);
  186. }
  187. }
  188. void DisconnectCallback ()
  189. {
  190. SocketError = SocketError.Success;
  191. LastOperation = SocketAsyncOperation.Disconnect;
  192. try {
  193. curSocket.Disconnect (DisconnectReuseSocket);
  194. } catch (SocketException ex) {
  195. SocketError = ex.SocketErrorCode;
  196. throw;
  197. } finally {
  198. OnCompleted (this);
  199. }
  200. }
  201. void ReceiveFromCallback ()
  202. {
  203. SocketError = SocketError.Success;
  204. LastOperation = SocketAsyncOperation.ReceiveFrom;
  205. try {
  206. EndPoint ep = RemoteEndPoint;
  207. BytesTransferred = curSocket.ReceiveFrom_nochecks (Buffer, Offset, Count, SocketFlags, ref ep);
  208. } catch (SocketException ex) {
  209. SocketError = ex.SocketErrorCode;
  210. throw;
  211. } finally {
  212. OnCompleted (this);
  213. }
  214. }
  215. void SendToCallback ()
  216. {
  217. SocketError = SocketError.Success;
  218. LastOperation = SocketAsyncOperation.SendTo;
  219. int total = 0;
  220. try {
  221. int count = Count;
  222. while (total < count)
  223. total += curSocket.SendTo_nochecks (Buffer, Offset, count, SocketFlags, RemoteEndPoint);
  224. BytesTransferred = total;
  225. } catch (SocketException ex) {
  226. SocketError = ex.SocketErrorCode;
  227. throw;
  228. } finally {
  229. OnCompleted (this);
  230. }
  231. }
  232. internal void DoOperation (SocketAsyncOperation operation, Socket socket)
  233. {
  234. ThreadStart callback;
  235. curSocket = socket;
  236. switch (operation) {
  237. case SocketAsyncOperation.Accept:
  238. callback = new ThreadStart (AcceptCallback);
  239. break;
  240. case SocketAsyncOperation.Receive:
  241. callback = new ThreadStart (ReceiveCallback);
  242. break;
  243. case SocketAsyncOperation.Connect:
  244. callback = new ThreadStart (ConnectCallback);
  245. break;
  246. case SocketAsyncOperation.Disconnect:
  247. callback = new ThreadStart (DisconnectCallback);
  248. break;
  249. case SocketAsyncOperation.ReceiveFrom:
  250. callback = new ThreadStart (ReceiveFromCallback);
  251. break;
  252. case SocketAsyncOperation.Send:
  253. callback = new ThreadStart (SendCallback);
  254. break;
  255. case SocketAsyncOperation.SendTo:
  256. callback = new ThreadStart (SendToCallback);
  257. break;
  258. default:
  259. throw new NotSupportedException ();
  260. break;
  261. }
  262. Thread t = new Thread (callback);
  263. t.IsBackground = true;
  264. t.Start ();
  265. }
  266. #endregion
  267. }
  268. }
  269. #endif