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;
501 public void Accept ()
504 Socket acc_socket = null;
506 if (args != null && args.AcceptSocket != null) {
507 result.Sock.Accept (args.AcceptSocket);
508 acc_socket = args.AcceptSocket;
510 acc_socket = result.Sock.Accept ();
512 args.AcceptSocket = acc_socket;
514 } catch (Exception e) {
519 result.Complete (acc_socket);
523 /* only used in 2.0 profile and newer, but
524 * leave in older profiles to keep interface
525 * to runtime consistent
527 public void AcceptReceive ()
530 Socket acc_socket = null;
532 if (result.AcceptSocket == null) {
533 acc_socket = result.Sock.Accept ();
535 acc_socket = result.AcceptSocket;
536 result.Sock.Accept (acc_socket);
538 } catch (Exception e) {
543 /* It seems the MS runtime
544 * special-cases 0-length requested
545 * receive data. See bug 464201.
548 if (result.Size > 0) {
551 total = acc_socket.Receive_nochecks (result.Buffer,
557 result.Complete (new SocketException ((int) error));
560 } catch (Exception e) {
566 result.Complete (acc_socket, total);
570 public void Connect ()
572 if (result.EndPoint == null) {
573 result.Complete (new SocketException ((int)SocketError.AddressNotAvailable));
577 SocketAsyncResult mconnect = result.AsyncState as SocketAsyncResult;
579 bool is_mconnect = (mconnect != null && mconnect.Addresses != null);
581 if (result.ErrorCode == SocketError.AccessDenied) {
583 result.DoMConnectCallback ();
586 bool is_mconnect = false;
590 EndPoint ep = result.EndPoint;
591 error_code = (int) result.Sock.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
592 if (error_code == 0) {
595 result.Sock.seed_endpoint = ep;
596 result.Sock.connected = true;
597 result.Sock.isbound = true;
598 result.Sock.connect_in_progress = false;
602 result.DoMConnectCallback ();
607 result.Sock.connect_in_progress = false;
608 result.Complete (new SocketException (error_code));
612 if (mconnect.CurrentAddress >= mconnect.Addresses.Length) {
613 mconnect.Complete (new SocketException (error_code));
615 mconnect.DoMConnectCallback ();
618 mconnect.Sock.BeginMConnect (mconnect);
619 } catch (Exception e) {
620 result.Sock.connect_in_progress = false;
625 result.DoMConnectCallback ();
630 /* Also only used in 2.0 profile and newer */
631 public void Disconnect ()
636 result.ReuseSocket = args.DisconnectReuseSocket;
637 result.Sock.Disconnect (result.ReuseSocket);
638 } catch (Exception e) {
646 public void Receive ()
648 if (result.operation == SocketOperation.ReceiveGeneric) {
652 // Actual recv() done in the runtime
656 public void ReceiveFrom ()
661 total = result.Sock.ReceiveFrom_nochecks (result.Buffer,
665 ref result.EndPoint);
666 } catch (Exception e) {
671 result.Complete (total);
675 public void ReceiveGeneric ()
679 total = result.Sock.Receive (result.Buffers, result.SockFlags);
680 } catch (Exception e) {
684 result.Complete (total);
689 void UpdateSendValues (int last_sent)
691 if (result.error == 0) {
692 send_so_far += last_sent;
693 result.Offset += last_sent;
694 result.Size -= last_sent;
700 if (result.operation == SocketOperation.SendGeneric) {
704 // Actual send() done in the runtime
705 if (result.error == 0) {
706 UpdateSendValues (result.Total);
707 if (result.Sock.disposed) {
712 if (result.Size > 0) {
713 Socket.socket_pool_queue (Worker.Dispatcher, result);
714 return; // Have to finish writing everything. See bug #74475.
716 result.Total = send_so_far;
722 public void SendTo ()
727 total = result.Sock.SendTo_nochecks (result.Buffer,
733 UpdateSendValues (total);
734 if (result.Size > 0) {
735 Socket.socket_pool_queue (Worker.Dispatcher, result);
736 return; // Have to finish writing everything. See bug #74475.
738 result.Total = send_so_far;
740 } catch (Exception e) {
750 public void SendGeneric ()
754 total = result.Sock.Send (result.Buffers, result.SockFlags);
755 } catch (Exception e) {
759 result.Complete (total);
763 private Queue readQ = new Queue (2);
764 private Queue writeQ = new Queue (2);
766 internal delegate void SocketAsyncCall (SocketAsyncResult sar);
769 * These two fields are looked up by name by the runtime, don't change
770 * their name without also updating the runtime code.
772 private static int ipv4Supported = -1, ipv6Supported = -1;
777 // initialize ipv4Supported and ipv6Supported
778 CheckProtocolSupport ();
781 internal static void CheckProtocolSupport ()
783 if(ipv4Supported == -1) {
785 Socket tmp = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
794 if (ipv6Supported == -1) {
796 #if CONFIGURATION_DEP
797 SettingsSection config;
798 config = (SettingsSection) System.Configuration.ConfigurationManager.GetSection ("system.net/settings");
800 ipv6Supported = config.Ipv6.Enabled ? -1 : 0;
802 NetConfig config = System.Configuration.ConfigurationSettings.GetConfig("system.net/settings") as NetConfig;
804 ipv6Supported = config.ipv6Enabled ? -1 : 0;
807 if (ipv6Supported != 0) {
809 Socket tmp = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
820 public static bool SupportsIPv4 {
822 CheckProtocolSupport();
823 return ipv4Supported == 1;
827 [ObsoleteAttribute ("Use OSSupportsIPv6 instead")]
828 public static bool SupportsIPv6 {
830 CheckProtocolSupport();
831 return ipv6Supported == 1;
835 public static bool OSSupportsIPv4 {
837 CheckProtocolSupport();
838 return ipv4Supported == 1;
843 public static bool OSSupportsIPv6 {
845 CheckProtocolSupport();
846 return ipv6Supported == 1;
850 public static bool OSSupportsIPv6 {
852 NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces ();
854 foreach (NetworkInterface adapter in nics) {
855 if (adapter.Supports (NetworkInterfaceComponent.IPv6))
863 /* the field "socket" is looked up by name by the runtime */
864 private IntPtr socket;
865 private AddressFamily address_family;
866 private SocketType socket_type;
867 private ProtocolType protocol_type;
868 internal bool blocking=true;
869 Thread blocking_thread;
870 private bool isbound;
871 /* When true, the socket was connected at the time of
872 * the last IO operation
874 private bool connected;
875 /* true if we called Close_internal */
877 internal bool disposed;
878 bool connect_in_progress;
881 * This EndPoint is used when creating new endpoints. Because
882 * there are many types of EndPoints possible,
883 * seed_endpoint.Create(addr) is used for creating new ones.
884 * As such, this value is set on Bind, SentTo, ReceiveFrom,
887 internal EndPoint seed_endpoint = null;
890 // Creates a new system socket, returning the handle
891 [MethodImplAttribute(MethodImplOptions.InternalCall)]
892 private extern IntPtr Socket_internal(AddressFamily family,
898 public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
900 #if NET_2_1 && !MOBILE
901 switch (addressFamily) {
902 case AddressFamily.InterNetwork: // ok
903 case AddressFamily.InterNetworkV6: // ok
904 case AddressFamily.Unknown: // SocketException will be thrown later (with right error #)
906 // case AddressFamily.Unspecified:
908 throw new ArgumentException ("addressFamily");
911 switch (socketType) {
912 case SocketType.Stream: // ok
913 case SocketType.Unknown: // SocketException will be thrown later (with right error #)
916 throw new ArgumentException ("socketType");
919 switch (protocolType) {
920 case ProtocolType.Tcp: // ok
921 case ProtocolType.Unspecified: // ok
922 case ProtocolType.Unknown: // SocketException will be thrown later (with right error #)
925 throw new ArgumentException ("protocolType");
928 address_family = addressFamily;
929 socket_type = socketType;
930 protocol_type = protocolType;
934 socket = Socket_internal (addressFamily, socketType, protocolType, out error);
936 throw new SocketException (error);
937 #if !NET_2_1 || MOBILE
948 public AddressFamily AddressFamily {
949 get { return address_family; }
953 [MethodImplAttribute(MethodImplOptions.InternalCall)]
954 private extern static void Blocking_internal(IntPtr socket,
959 public bool Blocking {
964 if (disposed && closed)
965 throw new ObjectDisposedException (GetType ().ToString ());
969 Blocking_internal (socket, value, out error);
972 throw new SocketException (error);
978 public bool Connected {
979 get { return connected; }
980 internal set { connected = value; }
983 public ProtocolType ProtocolType {
984 get { return protocol_type; }
987 public bool NoDelay {
989 if (disposed && closed)
990 throw new ObjectDisposedException (GetType ().ToString ());
994 return (int)(GetSocketOption (
995 SocketOptionLevel.Tcp,
996 SocketOptionName.NoDelay)) != 0;
1000 if (disposed && closed)
1001 throw new ObjectDisposedException (GetType ().ToString ());
1006 SocketOptionLevel.Tcp,
1007 SocketOptionName.NoDelay, value ? 1 : 0);
1011 public int ReceiveBufferSize {
1013 if (disposed && closed) {
1014 throw new ObjectDisposedException (GetType ().ToString ());
1016 return((int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer));
1019 if (disposed && closed) {
1020 throw new ObjectDisposedException (GetType ().ToString ());
1023 throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
1026 SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value);
1030 public int SendBufferSize {
1032 if (disposed && closed) {
1033 throw new ObjectDisposedException (GetType ().ToString ());
1035 return((int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendBuffer));
1038 if (disposed && closed) {
1039 throw new ObjectDisposedException (GetType ().ToString ());
1042 throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
1045 SetSocketOption (SocketOptionLevel.Socket,
1046 SocketOptionName.SendBuffer,
1053 if (disposed && closed) {
1054 throw new ObjectDisposedException (GetType ().ToString ());
1059 if (address_family == AddressFamily.InterNetwork) {
1060 ttl_val = (short)((int)GetSocketOption (SocketOptionLevel.IP, SocketOptionName.IpTimeToLive));
1061 } else if (address_family == AddressFamily.InterNetworkV6) {
1062 ttl_val = (short)((int)GetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.HopLimit));
1064 throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
1070 if (disposed && closed) {
1071 throw new ObjectDisposedException (GetType ().ToString ());
1074 throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
1077 if (address_family == AddressFamily.InterNetwork) {
1078 SetSocketOption (SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, value);
1079 } else if (address_family == AddressFamily.InterNetworkV6) {
1080 SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.HopLimit, value);
1082 throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
1087 // Returns the remote endpoint details in addr and port
1088 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1089 private extern static SocketAddress RemoteEndPoint_internal(IntPtr socket, int family, out int error);
1091 public EndPoint RemoteEndPoint {
1093 if (disposed && closed)
1094 throw new ObjectDisposedException (GetType ().ToString ());
1098 return seed_endpoint;
1101 * If the seed EndPoint is null, Connect, Bind,
1102 * etc has not yet been called. MS returns null
1105 if (!connected || seed_endpoint == null)
1111 sa=RemoteEndPoint_internal(socket, (int) address_family, out error);
1114 throw new SocketException (error);
1116 return seed_endpoint.Create (sa);
1120 void Linger (IntPtr handle)
1122 if (!connected || linger_timeout <= 0)
1125 // We don't want to receive any more data
1127 Shutdown_internal (handle, SocketShutdown.Receive, out error);
1131 int seconds = linger_timeout / 1000;
1132 int ms = linger_timeout % 1000;
1134 // If the other end closes, this will return 'true' with 'Available' == 0
1135 Poll_internal (handle, SelectMode.SelectRead, ms * 1000, out error);
1141 LingerOption linger = new LingerOption (true, seconds);
1142 SetSocketOption_internal (handle, SocketOptionLevel.Socket, SocketOptionName.Linger, linger, null, 0, out error);
1143 /* Not needed, we're closing upon return */
1149 protected virtual void Dispose (bool disposing)
1155 bool was_connected = connected;
1157 if ((int) socket != -1) {
1161 socket = (IntPtr) (-1);
1162 Thread th = blocking_thread;
1165 blocking_thread = null;
1170 //DateTime start = DateTime.UtcNow;
1171 Close_internal (x, out error);
1172 //Console.WriteLine ("Time spent in Close_internal: {0}ms", (DateTime.UtcNow - start).TotalMilliseconds);
1174 throw new SocketException (error);
1178 #if NET_2_1 || NET_4_0
1179 public void Dispose ()
1181 void IDisposable.Dispose ()
1185 GC.SuppressFinalize (this);
1188 // Closes the socket
1189 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1190 private extern static void Close_internal(IntPtr socket, out int error);
1192 public void Close ()
1195 ((IDisposable) this).Dispose ();
1198 public void Close (int timeout)
1200 linger_timeout = timeout;
1201 ((IDisposable) this).Dispose ();
1204 // Connects to the remote address
1205 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1206 private extern static void Connect_internal(IntPtr sock,
1210 public void Connect (EndPoint remoteEP)
1212 SocketAddress serial = null;
1214 if (disposed && closed)
1215 throw new ObjectDisposedException (GetType ().ToString ());
1217 if (remoteEP == null)
1218 throw new ArgumentNullException ("remoteEP");
1220 IPEndPoint ep = remoteEP as IPEndPoint;
1222 if (ep != null && socket_type != SocketType.Dgram) /* Dgram uses Any to 'disconnect' */
1226 if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any))
1227 throw new SocketException ((int) SocketError.AddressNotAvailable);
1230 if (protocol_type != ProtocolType.Tcp)
1231 throw new SocketException ((int) SocketError.AccessDenied);
1234 throw new InvalidOperationException ();
1236 serial = remoteEP.Serialize ();
1240 blocking_thread = Thread.CurrentThread;
1242 Connect_internal (socket, serial, out error);
1243 } catch (ThreadAbortException) {
1245 Thread.ResetAbort ();
1246 error = (int) SocketError.Interrupted;
1249 blocking_thread = null;
1252 if (error == 0 || error == 10035)
1253 seed_endpoint = remoteEP; // Keep the ep around for non-blocking sockets
1256 throw new SocketException (error);
1259 if (socket_type == SocketType.Dgram && (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)))
1269 public bool ReceiveAsync (SocketAsyncEventArgs e)
1271 // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1272 if (disposed && closed)
1273 throw new ObjectDisposedException (GetType ().ToString ());
1275 // LAME SPEC: the ArgumentException is never thrown, instead an NRE is
1276 // thrown when e.Buffer and e.BufferList are null (works fine when one is
1277 // set to a valid object)
1278 if (e.Buffer == null && e.BufferList == null)
1279 throw new NullReferenceException ("Either e.Buffer or e.BufferList must be valid buffers.");
1282 SocketOperation op = (e.Buffer != null) ? SocketOperation.Receive : SocketOperation.ReceiveGeneric;
1283 e.Worker.Init (this, e, op);
1284 SocketAsyncResult res = e.Worker.result;
1285 if (e.Buffer != null) {
1286 res.Buffer = e.Buffer;
1287 res.Offset = e.Offset;
1290 res.Buffers = e.BufferList;
1292 res.SockFlags = e.SocketFlags;
1295 readQ.Enqueue (e.Worker);
1296 count = readQ.Count;
1299 // Receive takes care of ReceiveGeneric
1300 socket_pool_queue (Worker.Dispatcher, res);
1306 public bool SendAsync (SocketAsyncEventArgs e)
1308 // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1309 if (disposed && closed)
1310 throw new ObjectDisposedException (GetType ().ToString ());
1311 if (e.Buffer == null && e.BufferList == null)
1312 throw new NullReferenceException ("Either e.Buffer or e.BufferList must be valid buffers.");
1315 SocketOperation op = (e.Buffer != null) ? SocketOperation.Send : SocketOperation.SendGeneric;
1316 e.Worker.Init (this, e, op);
1317 SocketAsyncResult res = e.Worker.result;
1318 if (e.Buffer != null) {
1319 res.Buffer = e.Buffer;
1320 res.Offset = e.Offset;
1323 res.Buffers = e.BufferList;
1325 res.SockFlags = e.SocketFlags;
1328 writeQ.Enqueue (e.Worker);
1329 count = writeQ.Count;
1332 // Send takes care of SendGeneric
1333 socket_pool_queue (Worker.Dispatcher, res);
1338 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1339 extern static bool Poll_internal (IntPtr socket, SelectMode mode, int timeout, out int error);
1341 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1342 private extern static int Receive_internal(IntPtr sock,
1349 internal int Receive_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
1352 int ret = Receive_internal (socket, buf, offset, size, flags, out nativeError);
1353 error = (SocketError) nativeError;
1354 if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress) {
1364 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1365 private extern static void GetSocketOption_obj_internal(IntPtr socket,
1366 SocketOptionLevel level, SocketOptionName name, out object obj_val,
1369 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1370 private extern static int Send_internal(IntPtr sock,
1371 byte[] buf, int offset,
1376 internal int Send_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
1379 error = SocketError.Success;
1385 int ret = Send_internal (socket, buf, offset, size, flags, out nativeError);
1387 error = (SocketError)nativeError;
1389 if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress) {
1399 public object GetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName)
1401 if (disposed && closed)
1402 throw new ObjectDisposedException (GetType ().ToString ());
1407 GetSocketOption_obj_internal (socket, optionLevel, optionName, out obj_val,
1410 throw new SocketException (error);
1412 if (optionName == SocketOptionName.Linger) {
1413 return((LingerOption)obj_val);
1414 } else if (optionName == SocketOptionName.AddMembership ||
1415 optionName == SocketOptionName.DropMembership) {
1416 return((MulticastOption)obj_val);
1417 } else if (obj_val is int) {
1418 return((int)obj_val);
1424 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1425 private extern static void Shutdown_internal (IntPtr socket, SocketShutdown how, out int error);
1427 public void Shutdown (SocketShutdown how)
1429 if (disposed && closed)
1430 throw new ObjectDisposedException (GetType ().ToString ());
1433 throw new SocketException (10057); // Not connected
1437 Shutdown_internal (socket, how, out error);
1439 throw new SocketException (error);
1442 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1443 private extern static void SetSocketOption_internal (IntPtr socket, SocketOptionLevel level,
1444 SocketOptionName name, object obj_val,
1445 byte [] byte_val, int int_val,
1448 public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
1450 if (disposed && closed)
1451 throw new ObjectDisposedException (GetType ().ToString ());
1455 SetSocketOption_internal (socket, optionLevel, optionName, null,
1456 null, optionValue, out error);
1459 throw new SocketException (error);
1462 private void ThrowIfUpd ()
1464 #if !NET_2_1 || MOBILE
1465 if (protocol_type == ProtocolType.Udp)
1466 throw new SocketException ((int)SocketError.ProtocolOption);
1473 IAsyncResult BeginConnect(EndPoint end_point, AsyncCallback callback, object state)
1475 if (disposed && closed)
1476 throw new ObjectDisposedException (GetType ().ToString ());
1478 if (end_point == null)
1479 throw new ArgumentNullException ("end_point");
1481 SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Connect);
1482 req.EndPoint = end_point;
1484 // Bug #75154: Connect() should not succeed for .Any addresses.
1485 if (end_point is IPEndPoint) {
1486 IPEndPoint ep = (IPEndPoint) end_point;
1487 if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)) {
1488 req.Complete (new SocketException ((int) SocketError.AddressNotAvailable), true);
1494 if (connect_in_progress) {
1495 // This could happen when multiple IPs are used
1496 // Calling connect() again will reset the connection attempt and cause
1497 // an error. Better to just close the socket and move on.
1498 connect_in_progress = false;
1499 Close_internal (socket, out error);
1500 socket = Socket_internal (address_family, socket_type, protocol_type, out error);
1502 throw new SocketException (error);
1504 bool blk = blocking;
1507 SocketAddress serial = end_point.Serialize ();
1508 Connect_internal (socket, serial, out error);
1515 req.Complete (true);
1519 if (error != (int) SocketError.InProgress && error != (int) SocketError.WouldBlock) {
1523 req.Complete (new SocketException (error), true);
1530 connect_in_progress = true;
1531 socket_pool_queue (Worker.Dispatcher, req);
1540 IAsyncResult BeginConnect (IPAddress[] addresses, int port, AsyncCallback callback, object state)
1543 if (disposed && closed)
1544 throw new ObjectDisposedException (GetType ().ToString ());
1546 if (addresses == null)
1547 throw new ArgumentNullException ("addresses");
1549 if (addresses.Length == 0)
1550 throw new ArgumentException ("Empty addresses list");
1552 if (this.AddressFamily != AddressFamily.InterNetwork &&
1553 this.AddressFamily != AddressFamily.InterNetworkV6)
1554 throw new NotSupportedException ("This method is only valid for addresses in the InterNetwork or InterNetworkV6 families");
1556 if (port <= 0 || port > 65535)
1557 throw new ArgumentOutOfRangeException ("port", "Must be > 0 and < 65536");
1560 throw new InvalidOperationException ();
1563 SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Connect);
1564 req.Addresses = addresses;
1567 return BeginMConnect (req);
1570 IAsyncResult BeginMConnect (SocketAsyncResult req)
1572 IAsyncResult ares = null;
1573 Exception exc = null;
1574 for (int i = req.CurrentAddress; i < req.Addresses.Length; i++) {
1575 IPAddress addr = req.Addresses [i];
1576 IPEndPoint ep = new IPEndPoint (addr, req.Port);
1578 req.CurrentAddress++;
1579 ares = BeginConnect (ep, null, req);
1580 if (ares.IsCompleted && ares.CompletedSynchronously) {
1581 ((SocketAsyncResult) ares).CheckIfThrowDelayedException ();
1582 req.DoMConnectCallback ();
1585 } catch (Exception e) {
1597 // Returns false when it is ok to use RemoteEndPoint
1598 // true when addresses must be used (and addresses could be null/empty)
1599 bool GetCheckedIPs (SocketAsyncEventArgs e, out IPAddress [] addresses)
1602 #if MOONLIGHT || NET_4_0
1603 // Connect to the first address that match the host name, like:
1604 // http://blogs.msdn.com/ncl/archive/2009/07/20/new-ncl-features-in-net-4-0-beta-2.aspx
1605 // while skipping entries that do not match the address family
1606 DnsEndPoint dep = (e.RemoteEndPoint as DnsEndPoint);
1608 addresses = Dns.GetHostAddresses (dep.Host);
1609 #if MOONLIGHT && !INSIDE_SYSTEM
1610 if (!e.PolicyRestricted && !SecurityManager.HasElevatedPermissions) {
1611 List<IPAddress> valid = new List<IPAddress> ();
1612 foreach (IPAddress a in addresses) {
1613 // if we're not downloading a socket policy then check the policy
1614 // and if we're not running with elevated permissions (SL4 OoB option)
1615 endpoint = new IPEndPoint (a, dep.Port);
1616 if (!CrossDomainPolicyManager.CheckEndPoint (endpoint, e.SocketClientAccessPolicyProtocol))
1620 if (valid.Count == 0)
1621 e.SocketError = SocketError.AccessDenied;
1622 addresses = valid.ToArray ();
1627 e.ConnectByNameError = null;
1628 #if MOONLIGHT && !INSIDE_SYSTEM
1629 if (!e.PolicyRestricted && !SecurityManager.HasElevatedPermissions) {
1630 if (CrossDomainPolicyManager.CheckEndPoint (e.RemoteEndPoint, e.SocketClientAccessPolicyProtocol))
1633 e.SocketError = SocketError.AccessDenied;
1639 return false; // < NET_4_0 -> use remote endpoint
1643 bool ConnectAsyncReal (SocketAsyncEventArgs e)
1645 bool use_remoteep = true;
1646 #if MOONLIGHT || NET_4_0
1647 IPAddress [] addresses = null;
1648 use_remoteep = !GetCheckedIPs (e, out addresses);
1651 bool policy_failed = (e.SocketError == SocketError.AccessDenied);
1654 Worker w = e.Worker;
1655 w.Init (this, e, SocketOperation.Connect);
1656 SocketAsyncResult result = w.result;
1658 if (policy_failed) {
1659 // SocketAsyncEventArgs.Completed must be called
1661 result.EndPoint = e.RemoteEndPoint;
1662 result.error = (int) SocketError.AccessDenied;
1664 socket_pool_queue (Worker.Dispatcher, result);
1668 IAsyncResult ares = null;
1671 result.EndPoint = e.RemoteEndPoint;
1672 ares = BeginConnect (e.RemoteEndPoint, SocketAsyncEventArgs.Dispatcher, e);
1674 #if MOONLIGHT || NET_4_0
1677 DnsEndPoint dep = (e.RemoteEndPoint as DnsEndPoint);
1678 result.Addresses = addresses;
1679 result.Port = dep.Port;
1681 ares = BeginConnect (addresses, dep.Port, SocketAsyncEventArgs.Dispatcher, e);
1684 if (ares.IsCompleted && ares.CompletedSynchronously) {
1685 ((SocketAsyncResult) ares).CheckIfThrowDelayedException ();
1688 } catch (Exception exc) {
1689 result.Complete (exc, true);
1696 public bool ConnectAsync (SocketAsyncEventArgs e)
1698 // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1699 if (disposed && closed)
1700 throw new ObjectDisposedException (GetType ().ToString ());
1702 throw new InvalidOperationException ("You may not perform this operation after calling the Listen method.");
1703 if (e.RemoteEndPoint == null)
1704 throw new ArgumentNullException ("remoteEP");
1706 return ConnectAsyncReal (e);
1710 static void CheckConnect (SocketAsyncEventArgs e)
1712 // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1714 if (e.RemoteEndPoint == null)
1715 throw new ArgumentNullException ("remoteEP");
1716 if (e.BufferList != null)
1717 throw new ArgumentException ("Multiple buffers cannot be used with this method.");
1720 public bool ConnectAsync (SocketAsyncEventArgs e)
1722 if (disposed && closed)
1723 throw new ObjectDisposedException (GetType ().ToString ());
1726 // if an address family is specified then they must match
1727 AddressFamily raf = e.RemoteEndPoint.AddressFamily;
1728 if ((raf != AddressFamily.Unspecified) && (raf != AddressFamily))
1729 throw new NotSupportedException ("AddressFamily mismatch between socket and endpoint");
1731 // connected, not yet connected or even policy denied, the Socket.RemoteEndPoint is always
1732 // available after the ConnectAsync call
1733 seed_endpoint = e.RemoteEndPoint;
1734 return ConnectAsyncReal (e);
1737 public static bool ConnectAsync (SocketType socketType, ProtocolType protocolType, SocketAsyncEventArgs e)
1739 // exception ordering requires to check before creating the socket (good thing resource wise too)
1742 // create socket based on the endpoint address family (if specified), otherwise default fo IPv4
1743 AddressFamily raf = e.RemoteEndPoint.AddressFamily;
1744 if (raf == AddressFamily.Unspecified)
1745 raf = AddressFamily.InterNetwork;
1746 Socket s = new Socket (raf, socketType, protocolType);
1747 return s.ConnectAsyncReal (e);
1750 public static void CancelConnectAsync (SocketAsyncEventArgs e)
1753 throw new ArgumentNullException ("e");
1755 // FIXME: this is canceling a synchronous connect, not an async one
1756 Socket s = e.ConnectSocket;
1757 if ((s != null) && (s.blocking_thread != null))
1758 s.blocking_thread.Abort ();
1761 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1762 private extern static int Receive_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error);
1768 int Receive (IList<ArraySegment<byte>> buffers)
1772 ret = Receive (buffers, SocketFlags.None, out error);
1773 if (error != SocketError.Success) {
1774 throw new SocketException ((int)error);
1779 [CLSCompliant (false)]
1785 int Receive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
1789 ret = Receive (buffers, socketFlags, out error);
1790 if (error != SocketError.Success) {
1791 throw new SocketException ((int)error);
1796 [CLSCompliant (false)]
1802 int Receive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
1804 if (disposed && closed)
1805 throw new ObjectDisposedException (GetType ().ToString ());
1807 if (buffers == null ||
1808 buffers.Count == 0) {
1809 throw new ArgumentNullException ("buffers");
1812 int numsegments = buffers.Count;
1816 /* Only example I can find of sending a byte
1817 * array reference directly into an internal
1819 * System.Runtime.Remoting/System.Runtime.Remoting.Channels.Ipc.Win32/NamedPipeSocket.cs,
1820 * so taking a lead from that...
1822 WSABUF[] bufarray = new WSABUF[numsegments];
1823 GCHandle[] gch = new GCHandle[numsegments];
1825 for(int i = 0; i < numsegments; i++) {
1826 ArraySegment<byte> segment = buffers[i];
1828 if (segment.Offset < 0 || segment.Count < 0 ||
1829 segment.Count > segment.Array.Length - segment.Offset)
1830 throw new ArgumentOutOfRangeException ("segment");
1832 gch[i] = GCHandle.Alloc (segment.Array, GCHandleType.Pinned);
1833 bufarray[i].len = segment.Count;
1834 bufarray[i].buf = Marshal.UnsafeAddrOfPinnedArrayElement (segment.Array, segment.Offset);
1838 ret = Receive_internal (socket, bufarray,
1842 for(int i = 0; i < numsegments; i++) {
1843 if (gch[i].IsAllocated) {
1849 errorCode = (SocketError)nativeError;
1853 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1854 private extern static int Send_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error);
1860 int Send (IList<ArraySegment<byte>> buffers)
1864 ret = Send (buffers, SocketFlags.None, out error);
1865 if (error != SocketError.Success) {
1866 throw new SocketException ((int)error);
1876 int Send (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
1880 ret = Send (buffers, socketFlags, out error);
1881 if (error != SocketError.Success) {
1882 throw new SocketException ((int)error);
1887 [CLSCompliant (false)]
1893 int Send (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
1895 if (disposed && closed)
1896 throw new ObjectDisposedException (GetType ().ToString ());
1897 if (buffers == null)
1898 throw new ArgumentNullException ("buffers");
1899 if (buffers.Count == 0)
1900 throw new ArgumentException ("Buffer is empty", "buffers");
1901 int numsegments = buffers.Count;
1905 WSABUF[] bufarray = new WSABUF[numsegments];
1906 GCHandle[] gch = new GCHandle[numsegments];
1907 for(int i = 0; i < numsegments; i++) {
1908 ArraySegment<byte> segment = buffers[i];
1910 if (segment.Offset < 0 || segment.Count < 0 ||
1911 segment.Count > segment.Array.Length - segment.Offset)
1912 throw new ArgumentOutOfRangeException ("segment");
1914 gch[i] = GCHandle.Alloc (segment.Array, GCHandleType.Pinned);
1915 bufarray[i].len = segment.Count;
1916 bufarray[i].buf = Marshal.UnsafeAddrOfPinnedArrayElement (segment.Array, segment.Offset);
1920 ret = Send_internal (socket, bufarray, socketFlags, out nativeError);
1922 for(int i = 0; i < numsegments; i++) {
1923 if (gch[i].IsAllocated) {
1928 errorCode = (SocketError)nativeError;
1932 Exception InvalidAsyncOp (string method)
1934 return new InvalidOperationException (method + " can only be called once per asynchronous operation");
1942 int EndReceive (IAsyncResult result)
1945 int bytesReceived = EndReceive (result, out error);
1946 if (error != SocketError.Success) {
1947 if (error != SocketError.WouldBlock && error != SocketError.InProgress)
1949 throw new SocketException ((int)error);
1951 return bytesReceived;
1959 int EndReceive (IAsyncResult asyncResult, out SocketError errorCode)
1961 if (disposed && closed)
1962 throw new ObjectDisposedException (GetType ().ToString ());
1964 if (asyncResult == null)
1965 throw new ArgumentNullException ("asyncResult");
1967 SocketAsyncResult req = asyncResult as SocketAsyncResult;
1969 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
1971 if (Interlocked.CompareExchange (ref req.EndCalled, 1, 0) == 1)
1972 throw InvalidAsyncOp ("EndReceive");
1973 if (!asyncResult.IsCompleted)
1974 asyncResult.AsyncWaitHandle.WaitOne ();
1976 errorCode = req.ErrorCode;
1977 // If no socket error occurred, call CheckIfThrowDelayedException in case there are other
1978 // kinds of exceptions that should be thrown.
1979 if (errorCode == SocketError.Success)
1980 req.CheckIfThrowDelayedException();
1990 int EndSend (IAsyncResult result)
1993 int bytesSent = EndSend (result, out error);
1994 if (error != SocketError.Success) {
1995 if (error != SocketError.WouldBlock && error != SocketError.InProgress)
1997 throw new SocketException ((int)error);
2007 int EndSend (IAsyncResult asyncResult, out SocketError errorCode)
2009 if (disposed && closed)
2010 throw new ObjectDisposedException (GetType ().ToString ());
2011 if (asyncResult == null)
2012 throw new ArgumentNullException ("asyncResult");
2014 SocketAsyncResult req = asyncResult as SocketAsyncResult;
2016 throw new ArgumentException ("Invalid IAsyncResult", "result");
2018 if (Interlocked.CompareExchange (ref req.EndCalled, 1, 0) == 1)
2019 throw InvalidAsyncOp ("EndSend");
2020 if (!asyncResult.IsCompleted)
2021 asyncResult.AsyncWaitHandle.WaitOne ();
2023 errorCode = req.ErrorCode;
2024 // If no socket error occurred, call CheckIfThrowDelayedException in case there are other
2025 // kinds of exceptions that should be thrown.
2026 if (errorCode == SocketError.Success)
2027 req.CheckIfThrowDelayedException ();
2032 // Used by Udpclient
2038 int EndReceiveFrom(IAsyncResult result, ref EndPoint end_point)
2040 if (disposed && closed)
2041 throw new ObjectDisposedException (GetType ().ToString ());
2044 throw new ArgumentNullException ("result");
2046 if (end_point == null)
2047 throw new ArgumentNullException ("remote_end");
2049 SocketAsyncResult req = result as SocketAsyncResult;
2051 throw new ArgumentException ("Invalid IAsyncResult", "result");
2053 if (Interlocked.CompareExchange (ref req.EndCalled, 1, 0) == 1)
2054 throw InvalidAsyncOp ("EndReceiveFrom");
2055 if (!result.IsCompleted)
2056 result.AsyncWaitHandle.WaitOne();
2058 req.CheckIfThrowDelayedException();
2059 end_point = req.EndPoint;
2063 [MethodImplAttribute(MethodImplOptions.InternalCall)]
2064 static extern void socket_pool_queue (SocketAsyncCall d, SocketAsyncResult r);