SocketAsyncEventArgs.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. [MonoTODO ("not supported in all cases")]
  41. public IList<ArraySegment<byte>> BufferList {
  42. get { return _bufferList; }
  43. set {
  44. if (Buffer != null)
  45. throw new ArgumentException ("Buffer and BufferList properties cannot both be non-null.");
  46. _bufferList = value;
  47. }
  48. }
  49. public int BytesTransferred { get; private set; }
  50. public int Count { get; private set; }
  51. public bool DisconnectReuseSocket { get; set; }
  52. public SocketAsyncOperation LastOperation { get; private set; }
  53. public int Offset { get; private set; }
  54. public IPPacketInformation ReceiveMessageFromPacketInfo { get; private set; }
  55. public EndPoint RemoteEndPoint { get; set; }
  56. public SendPacketsElement[] SendPacketsElements { get; set; }
  57. public TransmitFileOptions SendPacketsFlags { get; set; }
  58. public int SendPacketsSendSize { get; set; }
  59. public SocketError SocketError { get; set; }
  60. public SocketFlags SocketFlags { get; set; }
  61. public object UserToken { get; set; }
  62. Socket curSocket;
  63. #if NET_2_1
  64. public Socket ConnectSocket {
  65. get {
  66. switch (SocketError) {
  67. case SocketError.AccessDenied:
  68. return null;
  69. default:
  70. return curSocket;
  71. }
  72. }
  73. }
  74. #endif
  75. public SocketAsyncEventArgs ()
  76. {
  77. AcceptSocket = null;
  78. Buffer = null;
  79. BufferList = null;
  80. BytesTransferred = 0;
  81. Count = 0;
  82. DisconnectReuseSocket = false;
  83. LastOperation = SocketAsyncOperation.None;
  84. Offset = 0;
  85. RemoteEndPoint = null;
  86. SendPacketsElements = null;
  87. SendPacketsFlags = TransmitFileOptions.UseDefaultWorkerThread;
  88. SendPacketsSendSize = 0;
  89. SocketError = SocketError.Success;
  90. SocketFlags = SocketFlags.None;
  91. UserToken = null;
  92. }
  93. ~SocketAsyncEventArgs ()
  94. {
  95. Dispose (false);
  96. }
  97. void Dispose (bool disposing)
  98. {
  99. Socket acceptSocket = AcceptSocket;
  100. if (acceptSocket != null)
  101. acceptSocket.Close ();
  102. if (disposing)
  103. GC.SuppressFinalize (this);
  104. }
  105. public void Dispose ()
  106. {
  107. Dispose (true);
  108. }
  109. protected virtual void OnCompleted (SocketAsyncEventArgs e)
  110. {
  111. if (e == null)
  112. return;
  113. if (e.Completed != null)
  114. e.Completed (e.curSocket, e);
  115. }
  116. public void SetBuffer (int offset, int count)
  117. {
  118. SetBufferInternal (Buffer, offset, count);
  119. }
  120. public void SetBuffer (byte[] buffer, int offset, int count)
  121. {
  122. SetBufferInternal (buffer, offset, count);
  123. }
  124. void SetBufferInternal (byte[] buffer, int offset, int count)
  125. {
  126. if (buffer != null) {
  127. if (BufferList != null)
  128. throw new ArgumentException ("Buffer and BufferList properties cannot both be non-null.");
  129. int buflen = buffer.Length;
  130. if (offset < 0 || offset >= buflen)
  131. throw new ArgumentOutOfRangeException ("offset");
  132. if (count < 0 || count + offset > buflen)
  133. throw new ArgumentOutOfRangeException ("count");
  134. }
  135. Count = count;
  136. Offset = offset;
  137. Buffer = buffer;
  138. }
  139. #region Internals
  140. void ReceiveCallback ()
  141. {
  142. SocketError = SocketError.Success;
  143. LastOperation = SocketAsyncOperation.Receive;
  144. SocketError error = SocketError.Success;
  145. if (!curSocket.Connected) {
  146. SocketError = SocketError.NotConnected;
  147. return;
  148. }
  149. try {
  150. // FIXME: this does not support using BufferList
  151. BytesTransferred = curSocket.Receive_nochecks (Buffer, Offset, Count, SocketFlags, out error);
  152. } finally {
  153. SocketError = error;
  154. OnCompleted (this);
  155. }
  156. }
  157. void ConnectCallback ()
  158. {
  159. LastOperation = SocketAsyncOperation.Connect;
  160. #if NET_2_1
  161. if (SocketError == SocketError.AccessDenied) {
  162. curSocket.Connected = false;
  163. OnCompleted (this);
  164. return;
  165. }
  166. #endif
  167. SocketError = SocketError.Success;
  168. SocketError error = SocketError.Success;
  169. try {
  170. if (!curSocket.Blocking) {
  171. int success;
  172. curSocket.Poll (-1, SelectMode.SelectWrite, out success);
  173. SocketError = (SocketError)success;
  174. if (success == 0)
  175. curSocket.Connected = true;
  176. else
  177. return;
  178. } else {
  179. curSocket.seed_endpoint = RemoteEndPoint;
  180. curSocket.Connect (RemoteEndPoint);
  181. curSocket.Connected = true;
  182. }
  183. } catch (SocketException se){
  184. error = se.SocketErrorCode;
  185. } finally {
  186. SocketError = error;
  187. OnCompleted (this);
  188. }
  189. }
  190. void SendCallback ()
  191. {
  192. SocketError = SocketError.Success;
  193. LastOperation = SocketAsyncOperation.Send;
  194. SocketError error = SocketError.Success;
  195. if (!curSocket.Connected) {
  196. SocketError = SocketError.NotConnected;
  197. return;
  198. }
  199. try {
  200. if (Buffer != null) {
  201. BytesTransferred = curSocket.Send_nochecks (Buffer, Offset, Count, SocketFlags.None, out error);
  202. } else if (BufferList != null) {
  203. BytesTransferred = 0;
  204. foreach (ArraySegment<byte> asb in BufferList) {
  205. BytesTransferred += curSocket.Send_nochecks (asb.Array, asb.Offset, asb.Count,
  206. SocketFlags.None, out error);
  207. if (error != SocketError.Success)
  208. break;
  209. }
  210. }
  211. } finally {
  212. SocketError = error;
  213. OnCompleted (this);
  214. }
  215. }
  216. #if !NET_2_1
  217. void AcceptCallback ()
  218. {
  219. SocketError = SocketError.Success;
  220. LastOperation = SocketAsyncOperation.Accept;
  221. try {
  222. curSocket.Accept (AcceptSocket);
  223. } catch (SocketException ex) {
  224. SocketError = ex.SocketErrorCode;
  225. throw;
  226. } finally {
  227. OnCompleted (this);
  228. }
  229. }
  230. void DisconnectCallback ()
  231. {
  232. SocketError = SocketError.Success;
  233. LastOperation = SocketAsyncOperation.Disconnect;
  234. try {
  235. curSocket.Disconnect (DisconnectReuseSocket);
  236. } catch (SocketException ex) {
  237. SocketError = ex.SocketErrorCode;
  238. throw;
  239. } finally {
  240. OnCompleted (this);
  241. }
  242. }
  243. void ReceiveFromCallback ()
  244. {
  245. SocketError = SocketError.Success;
  246. LastOperation = SocketAsyncOperation.ReceiveFrom;
  247. try {
  248. EndPoint ep = RemoteEndPoint;
  249. BytesTransferred = curSocket.ReceiveFrom_nochecks (Buffer, Offset, Count, SocketFlags, ref ep);
  250. } catch (SocketException ex) {
  251. SocketError = ex.SocketErrorCode;
  252. throw;
  253. } finally {
  254. OnCompleted (this);
  255. }
  256. }
  257. void SendToCallback ()
  258. {
  259. SocketError = SocketError.Success;
  260. LastOperation = SocketAsyncOperation.SendTo;
  261. int total = 0;
  262. try {
  263. int count = Count;
  264. while (total < count)
  265. total += curSocket.SendTo_nochecks (Buffer, Offset, count, SocketFlags, RemoteEndPoint);
  266. BytesTransferred = total;
  267. } catch (SocketException ex) {
  268. SocketError = ex.SocketErrorCode;
  269. throw;
  270. } finally {
  271. OnCompleted (this);
  272. }
  273. }
  274. #endif
  275. internal void DoOperation (SocketAsyncOperation operation, Socket socket)
  276. {
  277. ThreadStart callback;
  278. curSocket = socket;
  279. switch (operation) {
  280. #if !NET_2_1
  281. case SocketAsyncOperation.Accept:
  282. callback = new ThreadStart (AcceptCallback);
  283. break;
  284. case SocketAsyncOperation.Disconnect:
  285. callback = new ThreadStart (DisconnectCallback);
  286. break;
  287. case SocketAsyncOperation.ReceiveFrom:
  288. callback = new ThreadStart (ReceiveFromCallback);
  289. break;
  290. case SocketAsyncOperation.SendTo:
  291. callback = new ThreadStart (SendToCallback);
  292. break;
  293. #endif
  294. case SocketAsyncOperation.Receive:
  295. callback = new ThreadStart (ReceiveCallback);
  296. break;
  297. case SocketAsyncOperation.Connect:
  298. callback = new ThreadStart (ConnectCallback);
  299. break;
  300. case SocketAsyncOperation.Send:
  301. callback = new ThreadStart (SendCallback);
  302. break;
  303. default:
  304. throw new NotSupportedException ();
  305. }
  306. Thread t = new Thread (callback);
  307. t.IsBackground = true;
  308. t.Start ();
  309. }
  310. #endregion
  311. }
  312. }
  313. #endif