1 // System.Net.Sockets.Socket.cs
4 // Phillip Pearson (pp@myelin.co.nz)
5 // Dick Porter <dick@ximian.com>
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // Sridhar Kulkarni (sridharkulkarni@gmail.com)
8 // Brian Nickel (brian.nickel@gmail.com)
10 // Copyright (C) 2001, 2002 Phillip Pearson and Ximian, Inc.
11 // http://www.myelin.co.nz
12 // (c) 2004-2011 Novell, Inc. (http://www.novell.com)
16 // Permission is hereby granted, free of charge, to any person obtaining
17 // a copy of this software and associated documentation files (the
18 // "Software"), to deal in the Software without restriction, including
19 // without limitation the rights to use, copy, modify, merge, publish,
20 // distribute, sublicense, and/or sell copies of the Software, and to
21 // permit persons to whom the Software is furnished to do so, subject to
22 // the following conditions:
24 // The above copyright notice and this permission notice shall be
25 // included in all copies or substantial portions of the Software.
27 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
31 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
32 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
38 using System.Collections;
39 using System.Collections.Generic;
40 using System.Runtime.CompilerServices;
41 using System.Runtime.InteropServices;
42 using System.Threading;
44 using System.Security;
48 using System.Net.Configuration;
49 using System.Net.NetworkInformation;
51 #if MOONLIGHT && !INSIDE_SYSTEM
52 using System.Net.Policy;
55 namespace System.Net.Sockets {
57 public partial class Socket : IDisposable {
58 [StructLayout (LayoutKind.Sequential)]
64 // Used by the runtime
65 internal enum SocketOperation {
82 [StructLayout (LayoutKind.Sequential)]
83 internal sealed class SocketAsyncResult: IAsyncResult
85 /* Same structure in the runtime */
87 Keep this in sync with MonoSocketAsyncResult in
88 metadata/socket-io.h and ProcessAsyncReader
89 in System.Diagnostics/Process.cs.
95 AsyncCallback callback; // used from the runtime
96 WaitHandle waithandle;
98 Exception delayedException;
100 public EndPoint EndPoint; // Connect,ReceiveFrom,SendTo
101 public byte [] Buffer; // Receive,ReceiveFrom,Send,SendTo
102 public int Offset; // Receive,ReceiveFrom,Send,SendTo
103 public int Size; // Receive,ReceiveFrom,Send,SendTo
104 public SocketFlags SockFlags; // Receive,ReceiveFrom,Send,SendTo
105 public Socket AcceptSocket; // AcceptReceive
106 public IPAddress[] Addresses; // Connect
107 public int Port; // Connect
108 public IList<ArraySegment<byte>> Buffers; // Receive, Send
109 public bool ReuseSocket; // Disconnect
117 public bool blocking;
119 public SocketOperation operation;
121 public int EndCalled;
123 // These fields are not in MonoSocketAsyncResult
124 public Worker Worker;
125 public int CurrentAddress; // Connect
127 public SocketAsyncResult ()
131 public void Init (Socket sock, object state, AsyncCallback callback, SocketOperation operation)
135 this.blocking = sock.blocking;
136 this.handle = sock.socket;
138 this.blocking = true;
139 this.handle = IntPtr.Zero;
142 this.callback = callback;
143 GC.KeepAlive (this.callback);
144 this.operation = operation;
145 SockFlags = SocketFlags.None;
146 if (waithandle != null)
147 ((ManualResetEvent) waithandle).Reset ();
149 delayedException = null;
164 completed_sync = false;
173 public void DoMConnectCallback ()
175 if (callback == null)
178 ThreadPool.QueueUserWorkItem (_ => { callback (this); }, null);
180 ThreadPool.UnsafeQueueUserWorkItem (_ => { callback (this); }, null);
184 public void Dispose ()
186 Init (null, null, null, 0);
187 if (waithandle != null) {
193 public SocketAsyncResult (Socket sock, object state, AsyncCallback callback, SocketOperation operation)
196 this.blocking = sock.blocking;
197 this.handle = sock.socket;
199 this.callback = callback;
200 GC.KeepAlive (this.callback);
201 this.operation = operation;
202 SockFlags = SocketFlags.None;
203 Worker = new Worker (this);
206 public void CheckIfThrowDelayedException ()
208 if (delayedException != null) {
209 Sock.connected = false;
210 throw delayedException;
214 Sock.connected = false;
215 throw new SocketException (error);
219 void CompleteAllOnDispose (Queue queue)
221 object [] pending = queue.ToArray ();
225 for (int i = 0; i < pending.Length; i++) {
226 Worker worker = (Worker) pending [i];
227 SocketAsyncResult ares = worker.result;
228 cb = new WaitCallback (ares.CompleteDisposed);
230 ThreadPool.QueueUserWorkItem (cb, null);
232 ThreadPool.UnsafeQueueUserWorkItem (cb, null);
237 void CompleteDisposed (object unused)
242 public void Complete ()
244 if (operation != SocketOperation.Receive && Sock.disposed)
245 delayedException = new ObjectDisposedException (Sock.GetType ().ToString ());
250 if (operation == SocketOperation.Receive ||
251 operation == SocketOperation.ReceiveFrom ||
252 operation == SocketOperation.ReceiveGeneric ||
253 operation == SocketOperation.Accept) {
255 } else if (operation == SocketOperation.Send ||
256 operation == SocketOperation.SendTo ||
257 operation == SocketOperation.SendGeneric) {
263 Worker worker = null;
264 SocketAsyncCall sac = null;
266 // queue.Count will only be 0 if the socket is closed while receive/send/accept
267 // operation(s) are pending and at least one call to this method is
268 // waiting on the lock while another one calls CompleteAllOnDispose()
270 queue.Dequeue (); // remove ourselves
271 if (queue.Count > 0) {
272 worker = (Worker) queue.Peek ();
273 if (!Sock.disposed) {
274 sac = Worker.Dispatcher;
276 CompleteAllOnDispose (queue);
282 Socket.socket_pool_queue (sac, worker.result);
284 // IMPORTANT: 'callback', if any is scheduled from unmanaged code
287 public void Complete (bool synch)
289 completed_sync = synch;
293 public void Complete (int total)
299 public void Complete (Exception e, bool synch)
301 completed_sync = synch;
302 delayedException = e;
306 public void Complete (Exception e)
308 delayedException = e;
312 public void Complete (Socket s)
318 public void Complete (Socket s, int total)
325 public object AsyncState {
331 public WaitHandle AsyncWaitHandle {
334 if (waithandle == null)
335 waithandle = new ManualResetEvent (completed);
345 public bool CompletedSynchronously {
347 return(completed_sync);
351 public bool IsCompleted {
358 if (waithandle != null && value) {
359 ((ManualResetEvent) waithandle).Set ();
365 public Socket Socket {
372 get { return total; }
373 set { total = value; }
376 public SocketError ErrorCode {
378 SocketException ex = delayedException as SocketException;
380 return(ex.SocketErrorCode);
383 return((SocketError)error);
385 return(SocketError.Success);
390 internal sealed class Worker
392 public SocketAsyncResult result;
393 SocketAsyncEventArgs args;
395 public Worker (SocketAsyncEventArgs args)
398 result = new SocketAsyncResult ();
399 result.Worker = this;
402 public Worker (SocketAsyncResult ares)
407 public void Dispose ()
409 if (result != null) {
416 public static SocketAsyncCall Dispatcher = new SocketAsyncCall (DispatcherCB);
418 static void DispatcherCB (SocketAsyncResult sar)
420 SocketOperation op = sar.operation;
421 if (op == Socket.SocketOperation.Receive || op == Socket.SocketOperation.ReceiveGeneric ||
422 op == Socket.SocketOperation.RecvJustCallback)
423 sar.Worker.Receive ();
424 else if (op == Socket.SocketOperation.Send || op == Socket.SocketOperation.SendGeneric ||
425 op == Socket.SocketOperation.SendJustCallback)
428 else if (op == Socket.SocketOperation.ReceiveFrom)
429 sar.Worker.ReceiveFrom ();
430 else if (op == Socket.SocketOperation.SendTo)
431 sar.Worker.SendTo ();
433 else if (op == Socket.SocketOperation.Connect)
434 sar.Worker.Connect ();
436 else if (op == Socket.SocketOperation.Accept)
437 sar.Worker.Accept ();
438 else if (op == Socket.SocketOperation.AcceptReceive)
439 sar.Worker.AcceptReceive ();
440 else if (op == Socket.SocketOperation.Disconnect)
441 sar.Worker.Disconnect ();
443 // SendPackets and ReceiveMessageFrom are not implemented yet
445 else if (op == Socket.SocketOperation.ReceiveMessageFrom)
446 async_op = SocketAsyncOperation.ReceiveMessageFrom;
447 else if (op == Socket.SocketOperation.SendPackets)
448 async_op = SocketAsyncOperation.SendPackets;
452 throw new NotImplementedException (String.Format ("Operation {0} is not implemented", op));
455 /* This is called when reusing a SocketAsyncEventArgs */
456 public void Init (Socket sock, SocketAsyncEventArgs args, SocketOperation op)
458 result.Init (sock, args, SocketAsyncEventArgs.Dispatcher, op);
459 result.Worker = this;
460 SocketAsyncOperation async_op;
463 // -SocketOperation.AcceptReceive not used in SocketAsyncEventArgs
464 // -SendPackets and ReceiveMessageFrom are not implemented yet
465 if (op == Socket.SocketOperation.Connect)
466 async_op = SocketAsyncOperation.Connect;
468 else if (op == Socket.SocketOperation.Accept)
469 async_op = SocketAsyncOperation.Accept;
470 else if (op == Socket.SocketOperation.Disconnect)
471 async_op = SocketAsyncOperation.Disconnect;
473 else if (op == Socket.SocketOperation.Receive || op == Socket.SocketOperation.ReceiveGeneric)
474 async_op = SocketAsyncOperation.Receive;
476 else if (op == Socket.SocketOperation.ReceiveFrom)
477 async_op = SocketAsyncOperation.ReceiveFrom;
480 else if (op == Socket.SocketOperation.ReceiveMessageFrom)
481 async_op = SocketAsyncOperation.ReceiveMessageFrom;
483 else if (op == Socket.SocketOperation.Send || op == Socket.SocketOperation.SendGeneric)
484 async_op = SocketAsyncOperation.Send;
487 else if (op == Socket.SocketOperation.SendPackets)
488 async_op = SocketAsyncOperation.SendPackets;
490 else if (op == Socket.SocketOperation.SendTo)
491 async_op = SocketAsyncOperation.SendTo;
494 throw new NotImplementedException (String.Format ("Operation {0} is not implemented", op));
496 args.SetLastOperation (async_op);
497 args.SocketError = SocketError.Success;
498 args.BytesTransferred = 0;
502 public void Accept ()
505 Socket acc_socket = null;
507 if (args != null && args.AcceptSocket != null) {
508 result.Sock.Accept (args.AcceptSocket);
509 acc_socket = args.AcceptSocket;
511 acc_socket = result.Sock.Accept ();
513 args.AcceptSocket = acc_socket;
515 } catch (Exception e) {
520 result.Complete (acc_socket);
524 /* only used in 2.0 profile and newer, but
525 * leave in older profiles to keep interface
526 * to runtime consistent
528 public void AcceptReceive ()
531 Socket acc_socket = null;
533 if (result.AcceptSocket == null) {
534 acc_socket = result.Sock.Accept ();
536 acc_socket = result.AcceptSocket;
537 result.Sock.Accept (acc_socket);
539 } catch (Exception e) {
544 /* It seems the MS runtime
545 * special-cases 0-length requested
546 * receive data. See bug 464201.
549 if (result.Size > 0) {
552 total = acc_socket.Receive_nochecks (result.Buffer,
558 result.Complete (new SocketException ((int) error));
561 } catch (Exception e) {
567 result.Complete (acc_socket, total);
571 public void Connect ()
573 if (result.EndPoint == null) {
574 result.Complete (new SocketException ((int)SocketError.AddressNotAvailable));
578 SocketAsyncResult mconnect = result.AsyncState as SocketAsyncResult;
580 bool is_mconnect = (mconnect != null && mconnect.Addresses != null);
582 if (result.ErrorCode == SocketError.AccessDenied) {
584 result.DoMConnectCallback ();
587 bool is_mconnect = false;
591 EndPoint ep = result.EndPoint;
592 error_code = (int) result.Sock.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
593 if (error_code == 0) {
596 result.Sock.seed_endpoint = ep;
597 result.Sock.connected = true;
598 result.Sock.isbound = true;
599 result.Sock.connect_in_progress = false;
603 result.DoMConnectCallback ();
608 result.Sock.connect_in_progress = false;
609 result.Complete (new SocketException (error_code));
613 if (mconnect.CurrentAddress >= mconnect.Addresses.Length) {
614 mconnect.Complete (new SocketException (error_code));
616 mconnect.DoMConnectCallback ();
619 mconnect.Sock.BeginMConnect (mconnect);
620 } catch (Exception e) {
621 result.Sock.connect_in_progress = false;
626 result.DoMConnectCallback ();
631 /* Also only used in 2.0 profile and newer */
632 public void Disconnect ()
637 result.ReuseSocket = args.DisconnectReuseSocket;
638 result.Sock.Disconnect (result.ReuseSocket);
639 } catch (Exception e) {
647 public void Receive ()
649 if (result.operation == SocketOperation.ReceiveGeneric) {
653 // Actual recv() done in the runtime
657 public void ReceiveFrom ()
662 total = result.Sock.ReceiveFrom_nochecks (result.Buffer,
666 ref result.EndPoint);
667 } catch (Exception e) {
672 result.Complete (total);
676 public void ReceiveGeneric ()
680 total = result.Sock.Receive (result.Buffers, result.SockFlags);
681 } catch (Exception e) {
685 result.Complete (total);
690 void UpdateSendValues (int last_sent)
692 if (result.error == 0) {
693 send_so_far += last_sent;
694 result.Offset += last_sent;
695 result.Size -= last_sent;
701 if (result.operation == SocketOperation.SendGeneric) {
705 // Actual send() done in the runtime
706 if (result.error == 0) {
707 UpdateSendValues (result.Total);
708 if (result.Sock.disposed) {
713 if (result.Size > 0) {
714 Socket.socket_pool_queue (Worker.Dispatcher, result);
715 return; // Have to finish writing everything. See bug #74475.
717 result.Total = send_so_far;
723 public void SendTo ()
728 total = result.Sock.SendTo_nochecks (result.Buffer,
734 UpdateSendValues (total);
735 if (result.Size > 0) {
736 Socket.socket_pool_queue (Worker.Dispatcher, result);
737 return; // Have to finish writing everything. See bug #74475.
739 result.Total = send_so_far;
741 } catch (Exception e) {
751 public void SendGeneric ()
755 total = result.Sock.Send (result.Buffers, result.SockFlags);
756 } catch (Exception e) {
760 result.Complete (total);
764 private Queue readQ = new Queue (2);
765 private Queue writeQ = new Queue (2);
767 internal delegate void SocketAsyncCall (SocketAsyncResult sar);
770 * These two fields are looked up by name by the runtime, don't change
771 * their name without also updating the runtime code.
773 private static int ipv4Supported = -1, ipv6Supported = -1;
778 // initialize ipv4Supported and ipv6Supported
779 CheckProtocolSupport ();
782 internal static void CheckProtocolSupport ()
784 if(ipv4Supported == -1) {
786 Socket tmp = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
795 if (ipv6Supported == -1) {
797 #if CONFIGURATION_DEP
798 SettingsSection config;
799 config = (SettingsSection) System.Configuration.ConfigurationManager.GetSection ("system.net/settings");
801 ipv6Supported = config.Ipv6.Enabled ? -1 : 0;
803 NetConfig config = System.Configuration.ConfigurationSettings.GetConfig("system.net/settings") as NetConfig;
805 ipv6Supported = config.ipv6Enabled ? -1 : 0;
808 if (ipv6Supported != 0) {
810 Socket tmp = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
821 public static bool SupportsIPv4 {
823 CheckProtocolSupport();
824 return ipv4Supported == 1;
828 [ObsoleteAttribute ("Use OSSupportsIPv6 instead")]
829 public static bool SupportsIPv6 {
831 CheckProtocolSupport();
832 return ipv6Supported == 1;
836 public static bool OSSupportsIPv4 {
838 CheckProtocolSupport();
839 return ipv4Supported == 1;
844 public static bool OSSupportsIPv6 {
846 CheckProtocolSupport();
847 return ipv6Supported == 1;
851 public static bool OSSupportsIPv6 {
853 NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces ();
855 foreach (NetworkInterface adapter in nics) {
856 if (adapter.Supports (NetworkInterfaceComponent.IPv6))
864 /* the field "socket" is looked up by name by the runtime */
865 private IntPtr socket;
866 private AddressFamily address_family;
867 private SocketType socket_type;
868 private ProtocolType protocol_type;
869 internal bool blocking=true;
870 Thread blocking_thread;
871 private bool isbound;
872 /* When true, the socket was connected at the time of
873 * the last IO operation
875 private bool connected;
876 /* true if we called Close_internal */
878 internal bool disposed;
879 bool connect_in_progress;
882 * This EndPoint is used when creating new endpoints. Because
883 * there are many types of EndPoints possible,
884 * seed_endpoint.Create(addr) is used for creating new ones.
885 * As such, this value is set on Bind, SentTo, ReceiveFrom,
888 internal EndPoint seed_endpoint = null;
891 // Creates a new system socket, returning the handle
892 [MethodImplAttribute(MethodImplOptions.InternalCall)]
893 private extern IntPtr Socket_internal(AddressFamily family,
899 public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
901 #if NET_2_1 && !MOBILE
902 switch (addressFamily) {
903 case AddressFamily.InterNetwork: // ok
904 case AddressFamily.InterNetworkV6: // ok
905 case AddressFamily.Unknown: // SocketException will be thrown later (with right error #)
907 // case AddressFamily.Unspecified:
909 throw new ArgumentException ("addressFamily");
912 switch (socketType) {
913 case SocketType.Stream: // ok
914 case SocketType.Unknown: // SocketException will be thrown later (with right error #)
917 throw new ArgumentException ("socketType");
920 switch (protocolType) {
921 case ProtocolType.Tcp: // ok
922 case ProtocolType.Unspecified: // ok
923 case ProtocolType.Unknown: // SocketException will be thrown later (with right error #)
926 throw new ArgumentException ("protocolType");
929 address_family = addressFamily;
930 socket_type = socketType;
931 protocol_type = protocolType;
935 socket = Socket_internal (addressFamily, socketType, protocolType, out error);
937 throw new SocketException (error);
938 #if !NET_2_1 || MOBILE
949 public AddressFamily AddressFamily {
950 get { return address_family; }
954 [MethodImplAttribute(MethodImplOptions.InternalCall)]
955 private extern static void Blocking_internal(IntPtr socket,
960 public bool Blocking {
965 if (disposed && closed)
966 throw new ObjectDisposedException (GetType ().ToString ());
970 Blocking_internal (socket, value, out error);
973 throw new SocketException (error);
979 public bool Connected {
980 get { return connected; }
981 internal set { connected = value; }
984 public ProtocolType ProtocolType {
985 get { return protocol_type; }
988 public bool NoDelay {
990 if (disposed && closed)
991 throw new ObjectDisposedException (GetType ().ToString ());
995 return (int)(GetSocketOption (
996 SocketOptionLevel.Tcp,
997 SocketOptionName.NoDelay)) != 0;
1001 if (disposed && closed)
1002 throw new ObjectDisposedException (GetType ().ToString ());
1007 SocketOptionLevel.Tcp,
1008 SocketOptionName.NoDelay, value ? 1 : 0);
1012 public int ReceiveBufferSize {
1014 if (disposed && closed) {
1015 throw new ObjectDisposedException (GetType ().ToString ());
1017 return((int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer));
1020 if (disposed && closed) {
1021 throw new ObjectDisposedException (GetType ().ToString ());
1024 throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
1027 SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value);
1031 public int SendBufferSize {
1033 if (disposed && closed) {
1034 throw new ObjectDisposedException (GetType ().ToString ());
1036 return((int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendBuffer));
1039 if (disposed && closed) {
1040 throw new ObjectDisposedException (GetType ().ToString ());
1043 throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
1046 SetSocketOption (SocketOptionLevel.Socket,
1047 SocketOptionName.SendBuffer,
1054 if (disposed && closed) {
1055 throw new ObjectDisposedException (GetType ().ToString ());
1060 if (address_family == AddressFamily.InterNetwork) {
1061 ttl_val = (short)((int)GetSocketOption (SocketOptionLevel.IP, SocketOptionName.IpTimeToLive));
1062 } else if (address_family == AddressFamily.InterNetworkV6) {
1063 ttl_val = (short)((int)GetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.HopLimit));
1065 throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
1071 if (disposed && closed) {
1072 throw new ObjectDisposedException (GetType ().ToString ());
1075 throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
1078 if (address_family == AddressFamily.InterNetwork) {
1079 SetSocketOption (SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, value);
1080 } else if (address_family == AddressFamily.InterNetworkV6) {
1081 SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.HopLimit, value);
1083 throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
1088 // Returns the remote endpoint details in addr and port
1089 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1090 private extern static SocketAddress RemoteEndPoint_internal(IntPtr socket, int family, out int error);
1092 public EndPoint RemoteEndPoint {
1094 if (disposed && closed)
1095 throw new ObjectDisposedException (GetType ().ToString ());
1099 return seed_endpoint;
1102 * If the seed EndPoint is null, Connect, Bind,
1103 * etc has not yet been called. MS returns null
1106 if (!connected || seed_endpoint == null)
1112 sa=RemoteEndPoint_internal(socket, (int) address_family, out error);
1115 throw new SocketException (error);
1117 return seed_endpoint.Create (sa);
1121 void Linger (IntPtr handle)
1123 if (!connected || linger_timeout <= 0)
1126 // We don't want to receive any more data
1128 Shutdown_internal (handle, SocketShutdown.Receive, out error);
1132 int seconds = linger_timeout / 1000;
1133 int ms = linger_timeout % 1000;
1135 // If the other end closes, this will return 'true' with 'Available' == 0
1136 Poll_internal (handle, SelectMode.SelectRead, ms * 1000, out error);
1142 LingerOption linger = new LingerOption (true, seconds);
1143 SetSocketOption_internal (handle, SocketOptionLevel.Socket, SocketOptionName.Linger, linger, null, 0, out error);
1144 /* Not needed, we're closing upon return */
1150 protected virtual void Dispose (bool disposing)
1156 bool was_connected = connected;
1158 if ((int) socket != -1) {
1162 socket = (IntPtr) (-1);
1163 Thread th = blocking_thread;
1166 blocking_thread = null;
1171 //DateTime start = DateTime.UtcNow;
1172 Close_internal (x, out error);
1173 //Console.WriteLine ("Time spent in Close_internal: {0}ms", (DateTime.UtcNow - start).TotalMilliseconds);
1175 throw new SocketException (error);
1179 #if NET_2_1 || NET_4_0
1180 public void Dispose ()
1182 void IDisposable.Dispose ()
1186 GC.SuppressFinalize (this);
1189 // Closes the socket
1190 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1191 private extern static void Close_internal(IntPtr socket, out int error);
1193 public void Close ()
1196 ((IDisposable) this).Dispose ();
1199 public void Close (int timeout)
1201 linger_timeout = timeout;
1202 ((IDisposable) this).Dispose ();
1205 // Connects to the remote address
1206 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1207 private extern static void Connect_internal(IntPtr sock,
1211 public void Connect (EndPoint remoteEP)
1213 SocketAddress serial = null;
1215 if (disposed && closed)
1216 throw new ObjectDisposedException (GetType ().ToString ());
1218 if (remoteEP == null)
1219 throw new ArgumentNullException ("remoteEP");
1221 IPEndPoint ep = remoteEP as IPEndPoint;
1223 if (ep != null && socket_type != SocketType.Dgram) /* Dgram uses Any to 'disconnect' */
1227 if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any))
1228 throw new SocketException ((int) SocketError.AddressNotAvailable);
1231 if (protocol_type != ProtocolType.Tcp)
1232 throw new SocketException ((int) SocketError.AccessDenied);
1235 throw new InvalidOperationException ();
1237 serial = remoteEP.Serialize ();
1241 blocking_thread = Thread.CurrentThread;
1243 Connect_internal (socket, serial, out error);
1244 } catch (ThreadAbortException) {
1246 Thread.ResetAbort ();
1247 error = (int) SocketError.Interrupted;
1250 blocking_thread = null;
1253 if (error == 0 || error == 10035)
1254 seed_endpoint = remoteEP; // Keep the ep around for non-blocking sockets
1257 throw new SocketException (error);
1260 if (socket_type == SocketType.Dgram && (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)))
1270 public bool ReceiveAsync (SocketAsyncEventArgs e)
1272 // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1273 if (disposed && closed)
1274 throw new ObjectDisposedException (GetType ().ToString ());
1276 // LAME SPEC: the ArgumentException is never thrown, instead an NRE is
1277 // thrown when e.Buffer and e.BufferList are null (works fine when one is
1278 // set to a valid object)
1279 if (e.Buffer == null && e.BufferList == null)
1280 throw new NullReferenceException ("Either e.Buffer or e.BufferList must be valid buffers.");
1283 SocketOperation op = (e.Buffer != null) ? SocketOperation.Receive : SocketOperation.ReceiveGeneric;
1284 e.Worker.Init (this, e, op);
1285 SocketAsyncResult res = e.Worker.result;
1286 if (e.Buffer != null) {
1287 res.Buffer = e.Buffer;
1288 res.Offset = e.Offset;
1291 res.Buffers = e.BufferList;
1293 res.SockFlags = e.SocketFlags;
1296 readQ.Enqueue (e.Worker);
1297 count = readQ.Count;
1300 // Receive takes care of ReceiveGeneric
1301 socket_pool_queue (Worker.Dispatcher, res);
1307 public bool SendAsync (SocketAsyncEventArgs e)
1309 // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1310 if (disposed && closed)
1311 throw new ObjectDisposedException (GetType ().ToString ());
1312 if (e.Buffer == null && e.BufferList == null)
1313 throw new NullReferenceException ("Either e.Buffer or e.BufferList must be valid buffers.");
1316 SocketOperation op = (e.Buffer != null) ? SocketOperation.Send : SocketOperation.SendGeneric;
1317 e.Worker.Init (this, e, op);
1318 SocketAsyncResult res = e.Worker.result;
1319 if (e.Buffer != null) {
1320 res.Buffer = e.Buffer;
1321 res.Offset = e.Offset;
1324 res.Buffers = e.BufferList;
1326 res.SockFlags = e.SocketFlags;
1329 writeQ.Enqueue (e.Worker);
1330 count = writeQ.Count;
1333 // Send takes care of SendGeneric
1334 socket_pool_queue (Worker.Dispatcher, res);
1339 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1340 extern static bool Poll_internal (IntPtr socket, SelectMode mode, int timeout, out int error);
1342 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1343 private extern static int Receive_internal(IntPtr sock,
1350 internal int Receive_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
1353 int ret = Receive_internal (socket, buf, offset, size, flags, out nativeError);
1354 error = (SocketError) nativeError;
1355 if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress) {
1365 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1366 private extern static void GetSocketOption_obj_internal(IntPtr socket,
1367 SocketOptionLevel level, SocketOptionName name, out object obj_val,
1370 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1371 private extern static int Send_internal(IntPtr sock,
1372 byte[] buf, int offset,
1377 internal int Send_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
1380 error = SocketError.Success;
1386 int ret = Send_internal (socket, buf, offset, size, flags, out nativeError);
1388 error = (SocketError)nativeError;
1390 if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress) {
1400 public object GetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName)
1402 if (disposed && closed)
1403 throw new ObjectDisposedException (GetType ().ToString ());
1408 GetSocketOption_obj_internal (socket, optionLevel, optionName, out obj_val,
1411 throw new SocketException (error);
1413 if (optionName == SocketOptionName.Linger) {
1414 return((LingerOption)obj_val);
1415 } else if (optionName == SocketOptionName.AddMembership ||
1416 optionName == SocketOptionName.DropMembership) {
1417 return((MulticastOption)obj_val);
1418 } else if (obj_val is int) {
1419 return((int)obj_val);
1425 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1426 private extern static void Shutdown_internal (IntPtr socket, SocketShutdown how, out int error);
1428 public void Shutdown (SocketShutdown how)
1430 if (disposed && closed)
1431 throw new ObjectDisposedException (GetType ().ToString ());
1434 throw new SocketException (10057); // Not connected
1438 Shutdown_internal (socket, how, out error);
1440 throw new SocketException (error);
1443 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1444 private extern static void SetSocketOption_internal (IntPtr socket, SocketOptionLevel level,
1445 SocketOptionName name, object obj_val,
1446 byte [] byte_val, int int_val,
1449 public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
1451 if (disposed && closed)
1452 throw new ObjectDisposedException (GetType ().ToString ());
1456 SetSocketOption_internal (socket, optionLevel, optionName, null,
1457 null, optionValue, out error);
1460 throw new SocketException (error);
1463 private void ThrowIfUpd ()
1465 #if !NET_2_1 || MOBILE
1466 if (protocol_type == ProtocolType.Udp)
1467 throw new SocketException ((int)SocketError.ProtocolOption);
1474 IAsyncResult BeginConnect(EndPoint end_point, AsyncCallback callback, object state)
1476 if (disposed && closed)
1477 throw new ObjectDisposedException (GetType ().ToString ());
1479 if (end_point == null)
1480 throw new ArgumentNullException ("end_point");
1482 SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Connect);
1483 req.EndPoint = end_point;
1485 // Bug #75154: Connect() should not succeed for .Any addresses.
1486 if (end_point is IPEndPoint) {
1487 IPEndPoint ep = (IPEndPoint) end_point;
1488 if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)) {
1489 req.Complete (new SocketException ((int) SocketError.AddressNotAvailable), true);
1495 if (connect_in_progress) {
1496 // This could happen when multiple IPs are used
1497 // Calling connect() again will reset the connection attempt and cause
1498 // an error. Better to just close the socket and move on.
1499 connect_in_progress = false;
1500 Close_internal (socket, out error);
1501 socket = Socket_internal (address_family, socket_type, protocol_type, out error);
1503 throw new SocketException (error);
1505 bool blk = blocking;
1508 SocketAddress serial = end_point.Serialize ();
1509 Connect_internal (socket, serial, out error);
1516 req.Complete (true);
1520 if (error != (int) SocketError.InProgress && error != (int) SocketError.WouldBlock) {
1524 req.Complete (new SocketException (error), true);
1531 connect_in_progress = true;
1532 socket_pool_queue (Worker.Dispatcher, req);
1541 IAsyncResult BeginConnect (IPAddress[] addresses, int port, AsyncCallback callback, object state)
1544 if (disposed && closed)
1545 throw new ObjectDisposedException (GetType ().ToString ());
1547 if (addresses == null)
1548 throw new ArgumentNullException ("addresses");
1550 if (addresses.Length == 0)
1551 throw new ArgumentException ("Empty addresses list");
1553 if (this.AddressFamily != AddressFamily.InterNetwork &&
1554 this.AddressFamily != AddressFamily.InterNetworkV6)
1555 throw new NotSupportedException ("This method is only valid for addresses in the InterNetwork or InterNetworkV6 families");
1557 if (port <= 0 || port > 65535)
1558 throw new ArgumentOutOfRangeException ("port", "Must be > 0 and < 65536");
1561 throw new InvalidOperationException ();
1564 SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Connect);
1565 req.Addresses = addresses;
1568 return BeginMConnect (req);
1571 IAsyncResult BeginMConnect (SocketAsyncResult req)
1573 IAsyncResult ares = null;
1574 Exception exc = null;
1575 for (int i = req.CurrentAddress; i < req.Addresses.Length; i++) {
1576 IPAddress addr = req.Addresses [i];
1577 IPEndPoint ep = new IPEndPoint (addr, req.Port);
1579 req.CurrentAddress++;
1580 ares = BeginConnect (ep, null, req);
1581 if (ares.IsCompleted && ares.CompletedSynchronously) {
1582 ((SocketAsyncResult) ares).CheckIfThrowDelayedException ();
1583 req.DoMConnectCallback ();
1586 } catch (Exception e) {
1598 // Returns false when it is ok to use RemoteEndPoint
1599 // true when addresses must be used (and addresses could be null/empty)
1600 bool GetCheckedIPs (SocketAsyncEventArgs e, out IPAddress [] addresses)
1603 #if MOONLIGHT || NET_4_0
1604 // Connect to the first address that match the host name, like:
1605 // http://blogs.msdn.com/ncl/archive/2009/07/20/new-ncl-features-in-net-4-0-beta-2.aspx
1606 // while skipping entries that do not match the address family
1607 DnsEndPoint dep = (e.RemoteEndPoint as DnsEndPoint);
1609 addresses = Dns.GetHostAddresses (dep.Host);
1610 #if MOONLIGHT && !INSIDE_SYSTEM
1611 if (!e.PolicyRestricted && !SecurityManager.HasElevatedPermissions) {
1612 List<IPAddress> valid = new List<IPAddress> ();
1613 foreach (IPAddress a in addresses) {
1614 // if we're not downloading a socket policy then check the policy
1615 // and if we're not running with elevated permissions (SL4 OoB option)
1616 endpoint = new IPEndPoint (a, dep.Port);
1617 if (!CrossDomainPolicyManager.CheckEndPoint (endpoint, e.SocketClientAccessPolicyProtocol))
1621 if (valid.Count == 0)
1622 e.SocketError = SocketError.AccessDenied;
1623 addresses = valid.ToArray ();
1628 e.ConnectByNameError = null;
1629 #if MOONLIGHT && !INSIDE_SYSTEM
1630 if (!e.PolicyRestricted && !SecurityManager.HasElevatedPermissions) {
1631 if (CrossDomainPolicyManager.CheckEndPoint (e.RemoteEndPoint, e.SocketClientAccessPolicyProtocol))
1634 e.SocketError = SocketError.AccessDenied;
1640 return false; // < NET_4_0 -> use remote endpoint
1644 bool ConnectAsyncReal (SocketAsyncEventArgs e)
1646 bool use_remoteep = true;
1647 #if MOONLIGHT || NET_4_0
1648 IPAddress [] addresses = null;
1649 use_remoteep = !GetCheckedIPs (e, out addresses);
1650 bool policy_failed = (e.SocketError == SocketError.AccessDenied);
1653 Worker w = e.Worker;
1654 w.Init (this, e, SocketOperation.Connect);
1655 SocketAsyncResult result = w.result;
1657 if (policy_failed) {
1658 // SocketAsyncEventArgs.Completed must be called
1660 result.EndPoint = e.RemoteEndPoint;
1661 result.error = (int) SocketError.AccessDenied;
1663 socket_pool_queue (Worker.Dispatcher, result);
1667 IAsyncResult ares = null;
1670 result.EndPoint = e.RemoteEndPoint;
1671 ares = BeginConnect (e.RemoteEndPoint, SocketAsyncEventArgs.Dispatcher, e);
1673 #if MOONLIGHT || NET_4_0
1676 DnsEndPoint dep = (e.RemoteEndPoint as DnsEndPoint);
1677 result.Addresses = addresses;
1678 result.Port = dep.Port;
1680 ares = BeginConnect (addresses, dep.Port, SocketAsyncEventArgs.Dispatcher, e);
1683 if (ares.IsCompleted && ares.CompletedSynchronously) {
1684 ((SocketAsyncResult) ares).CheckIfThrowDelayedException ();
1687 } catch (Exception exc) {
1688 result.Complete (exc, true);
1695 public bool ConnectAsync (SocketAsyncEventArgs e)
1697 // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1698 if (disposed && closed)
1699 throw new ObjectDisposedException (GetType ().ToString ());
1701 throw new InvalidOperationException ("You may not perform this operation after calling the Listen method.");
1702 if (e.RemoteEndPoint == null)
1703 throw new ArgumentNullException ("remoteEP");
1705 return ConnectAsyncReal (e);
1709 static void CheckConnect (SocketAsyncEventArgs e)
1711 // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1713 if (e.RemoteEndPoint == null)
1714 throw new ArgumentNullException ("remoteEP");
1715 if (e.BufferList != null)
1716 throw new ArgumentException ("Multiple buffers cannot be used with this method.");
1719 public bool ConnectAsync (SocketAsyncEventArgs e)
1721 if (disposed && closed)
1722 throw new ObjectDisposedException (GetType ().ToString ());
1725 // if an address family is specified then they must match
1726 AddressFamily raf = e.RemoteEndPoint.AddressFamily;
1727 if ((raf != AddressFamily.Unspecified) && (raf != AddressFamily))
1728 throw new NotSupportedException ("AddressFamily mismatch between socket and endpoint");
1730 // connected, not yet connected or even policy denied, the Socket.RemoteEndPoint is always
1731 // available after the ConnectAsync call
1732 seed_endpoint = e.RemoteEndPoint;
1733 return ConnectAsyncReal (e);
1736 public static bool ConnectAsync (SocketType socketType, ProtocolType protocolType, SocketAsyncEventArgs e)
1738 // exception ordering requires to check before creating the socket (good thing resource wise too)
1741 // create socket based on the endpoint address family (if specified), otherwise default fo IPv4
1742 AddressFamily raf = e.RemoteEndPoint.AddressFamily;
1743 if (raf == AddressFamily.Unspecified)
1744 raf = AddressFamily.InterNetwork;
1745 Socket s = new Socket (raf, socketType, protocolType);
1746 return s.ConnectAsyncReal (e);
1749 public static void CancelConnectAsync (SocketAsyncEventArgs e)
1752 throw new ArgumentNullException ("e");
1754 // FIXME: this is canceling a synchronous connect, not an async one
1755 Socket s = e.ConnectSocket;
1756 if ((s != null) && (s.blocking_thread != null))
1757 s.blocking_thread.Abort ();
1760 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1761 private extern static int Receive_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error);
1767 int Receive (IList<ArraySegment<byte>> buffers)
1771 ret = Receive (buffers, SocketFlags.None, out error);
1772 if (error != SocketError.Success) {
1773 throw new SocketException ((int)error);
1778 [CLSCompliant (false)]
1784 int Receive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
1788 ret = Receive (buffers, socketFlags, out error);
1789 if (error != SocketError.Success) {
1790 throw new SocketException ((int)error);
1795 [CLSCompliant (false)]
1801 int Receive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
1803 if (disposed && closed)
1804 throw new ObjectDisposedException (GetType ().ToString ());
1806 if (buffers == null ||
1807 buffers.Count == 0) {
1808 throw new ArgumentNullException ("buffers");
1811 int numsegments = buffers.Count;
1815 /* Only example I can find of sending a byte
1816 * array reference directly into an internal
1818 * System.Runtime.Remoting/System.Runtime.Remoting.Channels.Ipc.Win32/NamedPipeSocket.cs,
1819 * so taking a lead from that...
1821 WSABUF[] bufarray = new WSABUF[numsegments];
1822 GCHandle[] gch = new GCHandle[numsegments];
1824 for(int i = 0; i < numsegments; i++) {
1825 ArraySegment<byte> segment = buffers[i];
1827 if (segment.Offset < 0 || segment.Count < 0 ||
1828 segment.Count > segment.Array.Length - segment.Offset)
1829 throw new ArgumentOutOfRangeException ("segment");
1831 gch[i] = GCHandle.Alloc (segment.Array, GCHandleType.Pinned);
1832 bufarray[i].len = segment.Count;
1833 bufarray[i].buf = Marshal.UnsafeAddrOfPinnedArrayElement (segment.Array, segment.Offset);
1837 ret = Receive_internal (socket, bufarray,
1841 for(int i = 0; i < numsegments; i++) {
1842 if (gch[i].IsAllocated) {
1848 errorCode = (SocketError)nativeError;
1852 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1853 private extern static int Send_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error);
1859 int Send (IList<ArraySegment<byte>> buffers)
1863 ret = Send (buffers, SocketFlags.None, out error);
1864 if (error != SocketError.Success) {
1865 throw new SocketException ((int)error);
1875 int Send (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
1879 ret = Send (buffers, socketFlags, out error);
1880 if (error != SocketError.Success) {
1881 throw new SocketException ((int)error);
1886 [CLSCompliant (false)]
1892 int Send (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
1894 if (disposed && closed)
1895 throw new ObjectDisposedException (GetType ().ToString ());
1896 if (buffers == null)
1897 throw new ArgumentNullException ("buffers");
1898 if (buffers.Count == 0)
1899 throw new ArgumentException ("Buffer is empty", "buffers");
1900 int numsegments = buffers.Count;
1904 WSABUF[] bufarray = new WSABUF[numsegments];
1905 GCHandle[] gch = new GCHandle[numsegments];
1906 for(int i = 0; i < numsegments; i++) {
1907 ArraySegment<byte> segment = buffers[i];
1909 if (segment.Offset < 0 || segment.Count < 0 ||
1910 segment.Count > segment.Array.Length - segment.Offset)
1911 throw new ArgumentOutOfRangeException ("segment");
1913 gch[i] = GCHandle.Alloc (segment.Array, GCHandleType.Pinned);
1914 bufarray[i].len = segment.Count;
1915 bufarray[i].buf = Marshal.UnsafeAddrOfPinnedArrayElement (segment.Array, segment.Offset);
1919 ret = Send_internal (socket, bufarray, socketFlags, out nativeError);
1921 for(int i = 0; i < numsegments; i++) {
1922 if (gch[i].IsAllocated) {
1927 errorCode = (SocketError)nativeError;
1931 Exception InvalidAsyncOp (string method)
1933 return new InvalidOperationException (method + " can only be called once per asynchronous operation");
1941 int EndReceive (IAsyncResult result)
1944 int bytesReceived = EndReceive (result, out error);
1945 if (error != SocketError.Success) {
1946 if (error != SocketError.WouldBlock && error != SocketError.InProgress)
1948 throw new SocketException ((int)error);
1950 return bytesReceived;
1958 int EndReceive (IAsyncResult asyncResult, out SocketError errorCode)
1960 if (disposed && closed)
1961 throw new ObjectDisposedException (GetType ().ToString ());
1963 if (asyncResult == null)
1964 throw new ArgumentNullException ("asyncResult");
1966 SocketAsyncResult req = asyncResult as SocketAsyncResult;
1968 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
1970 if (Interlocked.CompareExchange (ref req.EndCalled, 1, 0) == 1)
1971 throw InvalidAsyncOp ("EndReceive");
1972 if (!asyncResult.IsCompleted)
1973 asyncResult.AsyncWaitHandle.WaitOne ();
1975 errorCode = req.ErrorCode;
1976 // If no socket error occurred, call CheckIfThrowDelayedException in case there are other
1977 // kinds of exceptions that should be thrown.
1978 if (errorCode == SocketError.Success)
1979 req.CheckIfThrowDelayedException();
1989 int EndSend (IAsyncResult result)
1992 int bytesSent = EndSend (result, out error);
1993 if (error != SocketError.Success) {
1994 if (error != SocketError.WouldBlock && error != SocketError.InProgress)
1996 throw new SocketException ((int)error);
2006 int EndSend (IAsyncResult asyncResult, out SocketError errorCode)
2008 if (disposed && closed)
2009 throw new ObjectDisposedException (GetType ().ToString ());
2010 if (asyncResult == null)
2011 throw new ArgumentNullException ("asyncResult");
2013 SocketAsyncResult req = asyncResult as SocketAsyncResult;
2015 throw new ArgumentException ("Invalid IAsyncResult", "result");
2017 if (Interlocked.CompareExchange (ref req.EndCalled, 1, 0) == 1)
2018 throw InvalidAsyncOp ("EndSend");
2019 if (!asyncResult.IsCompleted)
2020 asyncResult.AsyncWaitHandle.WaitOne ();
2022 errorCode = req.ErrorCode;
2023 // If no socket error occurred, call CheckIfThrowDelayedException in case there are other
2024 // kinds of exceptions that should be thrown.
2025 if (errorCode == SocketError.Success)
2026 req.CheckIfThrowDelayedException ();
2031 // Used by Udpclient
2037 int EndReceiveFrom(IAsyncResult result, ref EndPoint end_point)
2039 if (disposed && closed)
2040 throw new ObjectDisposedException (GetType ().ToString ());
2043 throw new ArgumentNullException ("result");
2045 if (end_point == null)
2046 throw new ArgumentNullException ("remote_end");
2048 SocketAsyncResult req = result as SocketAsyncResult;
2050 throw new ArgumentException ("Invalid IAsyncResult", "result");
2052 if (Interlocked.CompareExchange (ref req.EndCalled, 1, 0) == 1)
2053 throw InvalidAsyncOp ("EndReceiveFrom");
2054 if (!result.IsCompleted)
2055 result.AsyncWaitHandle.WaitOne();
2057 req.CheckIfThrowDelayedException();
2058 end_point = req.EndPoint;
2062 [MethodImplAttribute(MethodImplOptions.InternalCall)]
2063 static extern void socket_pool_queue (SocketAsyncCall d, SocketAsyncResult r);