SocketAsyncEventArgs.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. // System.Net.Sockets.SocketAsyncEventArgs.cs
  2. //
  3. // Authors:
  4. // Marek Habersack ([email protected])
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // Copyright (c) 2008,2010 Novell, Inc. (http://www.novell.com)
  8. // Copyright (c) 2011 Xamarin, Inc. (http://xamarin.com)
  9. //
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System;
  31. using System.Collections.Generic;
  32. using System.Reflection;
  33. using System.Security;
  34. using System.Threading;
  35. namespace System.Net.Sockets
  36. {
  37. public class SocketAsyncEventArgs : EventArgs, IDisposable
  38. {
  39. bool disposed;
  40. int in_progress;
  41. internal Socket.Worker Worker;
  42. EndPoint remote_ep;
  43. #if NET_4_0
  44. public Exception ConnectByNameError { get; internal set; }
  45. #endif
  46. public event EventHandler<SocketAsyncEventArgs> Completed;
  47. IList <ArraySegment <byte>> _bufferList;
  48. public Socket AcceptSocket { get; set; }
  49. public byte[] Buffer { get; private set; }
  50. public IList<ArraySegment<byte>> BufferList {
  51. get { return _bufferList; }
  52. set {
  53. if (Buffer != null && value != null)
  54. throw new ArgumentException ("Buffer and BufferList properties cannot both be non-null.");
  55. _bufferList = value;
  56. }
  57. }
  58. public int BytesTransferred { get; internal set; }
  59. public int Count { get; internal set; }
  60. public bool DisconnectReuseSocket { get; set; }
  61. public SocketAsyncOperation LastOperation { get; private set; }
  62. public int Offset { get; private set; }
  63. public EndPoint RemoteEndPoint {
  64. get { return remote_ep; }
  65. set { remote_ep = value; }
  66. }
  67. #if !NET_2_1
  68. public IPPacketInformation ReceiveMessageFromPacketInfo { get; private set; }
  69. public SendPacketsElement[] SendPacketsElements { get; set; }
  70. public TransmitFileOptions SendPacketsFlags { get; set; }
  71. #endif
  72. [MonoTODO ("unused property")]
  73. public int SendPacketsSendSize { get; set; }
  74. public SocketError SocketError { get; set; }
  75. public SocketFlags SocketFlags { get; set; }
  76. public object UserToken { get; set; }
  77. internal Socket curSocket;
  78. #if (NET_2_1 || NET_4_0)
  79. public Socket ConnectSocket {
  80. get {
  81. switch (SocketError) {
  82. case SocketError.AccessDenied:
  83. return null;
  84. default:
  85. return curSocket;
  86. }
  87. }
  88. }
  89. internal bool PolicyRestricted { get; private set; }
  90. internal SocketAsyncEventArgs (bool policy) :
  91. this ()
  92. {
  93. PolicyRestricted = policy;
  94. }
  95. #endif
  96. public SocketAsyncEventArgs ()
  97. {
  98. Worker = new Socket.Worker (this);
  99. AcceptSocket = null;
  100. Buffer = null;
  101. BufferList = null;
  102. BytesTransferred = 0;
  103. Count = 0;
  104. DisconnectReuseSocket = false;
  105. LastOperation = SocketAsyncOperation.None;
  106. Offset = 0;
  107. RemoteEndPoint = null;
  108. #if !NET_2_1
  109. SendPacketsElements = null;
  110. SendPacketsFlags = TransmitFileOptions.UseDefaultWorkerThread;
  111. #endif
  112. SendPacketsSendSize = -1;
  113. SocketError = SocketError.Success;
  114. SocketFlags = SocketFlags.None;
  115. UserToken = null;
  116. }
  117. ~SocketAsyncEventArgs ()
  118. {
  119. Dispose (false);
  120. }
  121. void Dispose (bool disposing)
  122. {
  123. disposed = true;
  124. if (disposing) {
  125. if (disposed || Interlocked.CompareExchange (ref in_progress, 0, 0) != 0)
  126. return;
  127. if (Worker != null) {
  128. Worker.Dispose ();
  129. Worker = null;
  130. }
  131. }
  132. AcceptSocket = null;
  133. Buffer = null;
  134. BufferList = null;
  135. RemoteEndPoint = null;
  136. UserToken = null;
  137. #if !NET_2_1
  138. SendPacketsElements = null;
  139. #endif
  140. }
  141. public void Dispose ()
  142. {
  143. Dispose (true);
  144. GC.SuppressFinalize (this);
  145. }
  146. internal void SetLastOperation (SocketAsyncOperation op)
  147. {
  148. if (disposed)
  149. throw new ObjectDisposedException ("System.Net.Sockets.SocketAsyncEventArgs");
  150. if (Interlocked.Exchange (ref in_progress, 1) != 0)
  151. throw new InvalidOperationException ("Operation already in progress");
  152. LastOperation = op;
  153. }
  154. protected virtual void OnCompleted (SocketAsyncEventArgs e)
  155. {
  156. if (e == null)
  157. return;
  158. EventHandler<SocketAsyncEventArgs> handler = e.Completed;
  159. if (handler != null)
  160. handler (e.curSocket, e);
  161. }
  162. public void SetBuffer (int offset, int count)
  163. {
  164. SetBufferInternal (Buffer, offset, count);
  165. }
  166. public void SetBuffer (byte[] buffer, int offset, int count)
  167. {
  168. SetBufferInternal (buffer, offset, count);
  169. }
  170. void SetBufferInternal (byte[] buffer, int offset, int count)
  171. {
  172. if (buffer != null) {
  173. if (BufferList != null)
  174. throw new ArgumentException ("Buffer and BufferList properties cannot both be non-null.");
  175. int buflen = buffer.Length;
  176. if (offset < 0 || (offset != 0 && offset >= buflen))
  177. throw new ArgumentOutOfRangeException ("offset");
  178. if (count < 0 || count > buflen - offset)
  179. throw new ArgumentOutOfRangeException ("count");
  180. Count = count;
  181. Offset = offset;
  182. }
  183. Buffer = buffer;
  184. }
  185. #region Internals
  186. internal static AsyncCallback Dispatcher = new AsyncCallback (DispatcherCB);
  187. static void DispatcherCB (IAsyncResult ares)
  188. {
  189. SocketAsyncEventArgs args = (SocketAsyncEventArgs) ares.AsyncState;
  190. if (Interlocked.Exchange (ref args.in_progress, 0) != 1)
  191. throw new InvalidOperationException ("No operation in progress");
  192. SocketAsyncOperation op = args.LastOperation;
  193. // Notes;
  194. // -SocketOperation.AcceptReceive not used in SocketAsyncEventArgs
  195. // -SendPackets and ReceiveMessageFrom are not implemented yet
  196. if (op == SocketAsyncOperation.Receive)
  197. args.ReceiveCallback (ares);
  198. else if (op == SocketAsyncOperation.Send)
  199. args.SendCallback (ares);
  200. else if (op == SocketAsyncOperation.ReceiveFrom)
  201. args.ReceiveFromCallback (ares);
  202. else if (op == SocketAsyncOperation.SendTo)
  203. args.SendToCallback (ares);
  204. else if (op == SocketAsyncOperation.Accept)
  205. args.AcceptCallback (ares);
  206. else if (op == SocketAsyncOperation.Disconnect)
  207. args.DisconnectCallback (ares);
  208. else if (op == SocketAsyncOperation.Connect)
  209. args.ConnectCallback ();
  210. /*
  211. else if (op == Socket.SocketOperation.ReceiveMessageFrom)
  212. else if (op == Socket.SocketOperation.SendPackets)
  213. */
  214. else
  215. throw new NotImplementedException (String.Format ("Operation {0} is not implemented", op));
  216. }
  217. internal void ReceiveCallback (IAsyncResult ares)
  218. {
  219. try {
  220. BytesTransferred = curSocket.EndReceive (ares);
  221. } catch (SocketException se){
  222. SocketError = se.SocketErrorCode;
  223. } catch (ObjectDisposedException) {
  224. SocketError = SocketError.OperationAborted;
  225. } finally {
  226. OnCompleted (this);
  227. }
  228. }
  229. void ConnectCallback ()
  230. {
  231. try {
  232. SocketError = (SocketError) Worker.result.error;
  233. } finally {
  234. OnCompleted (this);
  235. }
  236. }
  237. internal void SendCallback (IAsyncResult ares)
  238. {
  239. try {
  240. BytesTransferred = curSocket.EndSend (ares);
  241. } catch (SocketException se){
  242. SocketError = se.SocketErrorCode;
  243. } catch (ObjectDisposedException) {
  244. SocketError = SocketError.OperationAborted;
  245. } finally {
  246. OnCompleted (this);
  247. }
  248. }
  249. internal void AcceptCallback (IAsyncResult ares)
  250. {
  251. try {
  252. AcceptSocket = curSocket.EndAccept (ares);
  253. } catch (SocketException ex) {
  254. SocketError = ex.SocketErrorCode;
  255. } catch (ObjectDisposedException) {
  256. SocketError = SocketError.OperationAborted;
  257. } finally {
  258. if (AcceptSocket == null)
  259. AcceptSocket = new Socket (curSocket.AddressFamily, curSocket.SocketType, curSocket.ProtocolType, (IntPtr)(-1));
  260. OnCompleted (this);
  261. }
  262. }
  263. internal void DisconnectCallback (IAsyncResult ares)
  264. {
  265. try {
  266. curSocket.EndDisconnect (ares);
  267. } catch (SocketException ex) {
  268. SocketError = ex.SocketErrorCode;
  269. } catch (ObjectDisposedException) {
  270. SocketError = SocketError.OperationAborted;
  271. } finally {
  272. OnCompleted (this);
  273. }
  274. }
  275. internal void ReceiveFromCallback (IAsyncResult ares)
  276. {
  277. try {
  278. BytesTransferred = curSocket.EndReceiveFrom (ares, ref remote_ep);
  279. } catch (SocketException ex) {
  280. SocketError = ex.SocketErrorCode;
  281. } catch (ObjectDisposedException) {
  282. SocketError = SocketError.OperationAborted;
  283. } finally {
  284. OnCompleted (this);
  285. }
  286. }
  287. internal void SendToCallback (IAsyncResult ares)
  288. {
  289. try {
  290. BytesTransferred = curSocket.EndSendTo (ares);
  291. } catch (SocketException ex) {
  292. SocketError = ex.SocketErrorCode;
  293. } catch (ObjectDisposedException) {
  294. SocketError = SocketError.OperationAborted;
  295. } finally {
  296. OnCompleted (this);
  297. }
  298. }
  299. #endregion
  300. }
  301. }