internal SocketToken BeginConnect(EndPoint endpoint, ISocketCallback callback, ConnectionMultiplexer multiplexer, TextWriter log) { var addressFamily = endpoint.AddressFamily == AddressFamily.Unspecified ? AddressFamily.InterNetwork : endpoint.AddressFamily; var socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp); SetFastLoopbackOption(socket); socket.NoDelay = true; try { CompletionType connectCompletionType = CompletionType.Any; this.ShouldForceConnectCompletionType(ref connectCompletionType); var formattedEndpoint = Format.ToString(endpoint); var tuple = Tuple.Create(socket, callback); if (endpoint is DnsEndPoint) { // A work-around for a Mono bug in BeginConnect(EndPoint endpoint, AsyncCallback callback, object state) DnsEndPoint dnsEndpoint = (DnsEndPoint)endpoint; #if CORE_CLR multiplexer.LogLocked(log, "BeginConnect: {0}", formattedEndpoint); socket.ConnectAsync(dnsEndpoint.Host, dnsEndpoint.Port).ContinueWith(t => { multiplexer.LogLocked(log, "EndConnect: {0}", formattedEndpoint); EndConnectImpl(t, multiplexer, log, tuple); multiplexer.LogLocked(log, "Connect complete: {0}", formattedEndpoint); }); #else CompletionTypeHelper.RunWithCompletionType( cb => { multiplexer.LogLocked(log, "BeginConnect: {0}", formattedEndpoint); return(socket.BeginConnect(dnsEndpoint.Host, dnsEndpoint.Port, cb, tuple)); }, ar => { multiplexer.LogLocked(log, "EndConnect: {0}", formattedEndpoint); EndConnectImpl(ar, multiplexer, log, tuple); multiplexer.LogLocked(log, "Connect complete: {0}", formattedEndpoint); }, connectCompletionType); #endif } else { #if CORE_CLR multiplexer.LogLocked(log, "BeginConnect: {0}", formattedEndpoint); socket.ConnectAsync(endpoint).ContinueWith(t => { multiplexer.LogLocked(log, "EndConnect: {0}", formattedEndpoint); EndConnectImpl(t, multiplexer, log, tuple); }); #else CompletionTypeHelper.RunWithCompletionType( cb => { multiplexer.LogLocked(log, "BeginConnect: {0}", formattedEndpoint); return(socket.BeginConnect(endpoint, cb, tuple)); }, ar => { multiplexer.LogLocked(log, "EndConnect: {0}", formattedEndpoint); EndConnectImpl(ar, multiplexer, log, tuple); multiplexer.LogLocked(log, "Connect complete: {0}", formattedEndpoint); }, connectCompletionType); #endif } } catch (NotImplementedException ex) { if (!(endpoint is IPEndPoint)) { throw new InvalidOperationException("BeginConnect failed with NotImplementedException; consider using IP endpoints, or enable ResolveDns in the configuration", ex); } throw; } var token = new SocketToken(socket); return(token); }