/// <summary> /// Connect asyncronously to <param name="endPoint"></param> /// </summary> /// <param name="tcpClient"><see cref="TcpClient"/> object to connect with</param> /// <param name="endPoint"></param> /// <returns></returns> /// <exception cref="ArgumentException">if <param name="endPoint"/> is not a /// <see cref="DnsEndPoint"/> nor an <see cref="IPEndPoint"/></exception> public static Task ConnectAsync(this TcpClient tcpClient, EndPoint endPoint) { if (tcpClient == null) throw new ArgumentNullException("tcpClient"); if (endPoint == null) throw new ArgumentNullException("endPoint"); var dnsEndPoint = endPoint as DnsEndPoint; if (dnsEndPoint != null) return tcpClient.ConnectAsync(dnsEndPoint.Host, dnsEndPoint.Port); var ipEndPoint = endPoint as IPEndPoint; if (ipEndPoint != null) return tcpClient.ConnectAsync(ipEndPoint.Address, ipEndPoint.Port); throw new ArgumentException("Unsupported EndPoint type", "endpoint"); }
/// <summary> /// Connects the client to the given remote address and port, using a maximum timeout. The client /// will be closed when the timeout has passed and the client is still not connected /// </summary> /// <param name="client">The client.</param> /// <param name="address">The address to connect to.</param> /// <param name="port">The port to connect to.</param> /// <param name="timeout">The timeout in ms. Set to 0 to skip timeouts</param> /// <exception cref="System.IO.IOException">When a timeout has occured. In this case the socket will have been closed.</exception> public static async Task ConnectAsync(this TcpClient client, IPAddress address, int port, int timeout) { //create connection timeout token var token = timeout > 0 ? new CancellationTokenSource(timeout).Token : CancellationToken.None; try { //close connection when timeout is invoked using(token.Register(cl => ((TcpClient)cl).Close(), client)) { await client.ConnectAsync(address, port).AutoConfigureAwait(); } } catch(Exception ex) { if(token.IsCancellationRequested) { var error = string.Format("Connection to {0}:{1} could not be established within set timeout", address, port); throw new IOException(error, ex); } throw; } }
public static async Task ConnectTaskAsync(this Socket socket, SocketAsyncEventArgs socketAsyncEventArgs) { var task = CreateTaskFromCompletionHandler(socketAsyncEventArgs, SocketAsyncOperation.Connect); socket.ConnectAsync(socketAsyncEventArgs); await task; }
public static Lazy<IEventStoreConnection> AsLazy(this IEventStoreConnection connection) { return new Lazy<IEventStoreConnection>(() => { connection.ConnectAsync().Wait(TimeSpan.FromSeconds(10)); return connection; }, LazyThreadSafetyMode.ExecutionAndPublication); }
public static SocketAwaitable ConnectAsync(this Socket socket, SocketAwaitable awaitable) { awaitable.Reset(); if (!socket.ConnectAsync(awaitable.EventArgs)) awaitable.WasCompleted = true; return awaitable; }
/// <summary> /// Requests a remote host connection asynchronously. /// </summary> /// <param name="client">The TCP client to be connected.</param> /// <param name="host">The name of the remote host.</param> /// <param name="port">The port number of the remote host.</param> /// <returns>An observable containing a single notification when <paramref name="client"/> is connected.</returns> public static IObservable<Unit> ConnectObservable(this TcpClient client, string host, int port) { Contract.Requires(client != null); Contract.Requires(host != null); Contract.Requires(port >= IPEndPoint.MinPort && port <= IPEndPoint.MaxPort); Contract.Ensures(Contract.Result<IObservable<Unit>>() != null); return client.ConnectAsync(host, port).ToObservable(); }
internal static Task<bool> ConnectAsync(this Socket socket, IPAddress target, int port) { var tcs = new TaskCompletionSource<bool>(); var ce = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(target, port), UserToken = tcs }; ce.Completed += ConnectCompleted; if (socket.ConnectAsync(ce)) return tcs.Task; return _ConnectAsyncResultCache; }
/// <summary> /// Requests a remote host connection asynchronously. /// </summary> /// <param name="client">The TCP client to be connected.</param> /// <param name="addresses">At least one IP address that designates the remote host.</param> /// <param name="port">The port number of the remote host.</param> /// <returns>An observable containing a single notification when <paramref name="client"/> is connected.</returns> public static IObservable<Unit> ConnectObservable(this TcpClient client, IPAddress[] addresses, int port) { Contract.Requires(client != null); Contract.Requires(addresses != null); Contract.Requires(addresses.Length > 0); Contract.Requires(port >= IPEndPoint.MinPort && port <= IPEndPoint.MaxPort); Contract.Ensures(Contract.Result<IObservable<Unit>>() != null); return client.ConnectAsync(addresses, port).ToObservable(); }
public static Task ConnectTaskAsync (this BandClientManager manager, BandClient client) { var tcs = new TaskCompletionSource<object> (); EventHandler<ClientManagerConnectedEventArgs> onConnected = null; EventHandler<ClientManagerDisconnectedEventArgs> onDisconnect = null; EventHandler<ClientManagerFailedToConnectEventArgs> onFailed = null; // setup the completed event onConnected = (sender, args) => { if (args.Client == client) { manager.Connected -= onConnected; manager.Disconnected -= onDisconnect; manager.ConnectionFailed -= onFailed; // we are finished tcs.SetResult (null); } }; manager.Connected += onConnected; // setup the canceled event onDisconnect = (sender, args) => { if (args.Client == client) { manager.Connected -= onConnected; manager.Disconnected -= onDisconnect; manager.ConnectionFailed -= onFailed; // we were canceled tcs.SetCanceled(); } }; manager.Disconnected += onDisconnect; // setup the failed event onFailed = (sender, args) => { if (args.Client == client) { manager.Connected -= onConnected; manager.Disconnected -= onDisconnect; manager.ConnectionFailed -= onFailed; // we failed tcs.SetException (new BandException(args.Error)); } }; manager.ConnectionFailed += onFailed; // run async manager.ConnectAsync (client); return tcs.Task; }
public static async Task<bool> TryConnectAsync(this TcpClient tcpClient, IPAddress address, int port, int timeout, CancellationToken token) { var connectTask = tcpClient.ConnectAsync(address, port); var timeoutTask = Task.Delay(timeout, token); await Task.WhenAny(connectTask, timeoutTask); if (connectTask.IsCompleted) return true; tcpClient.Close(); return false; }
public static void ConnectAsync(this Socket socket, SocketAsyncEventArgs eventArgs, EndPoint remoteEndpoint, Action handler) { EventHandler<SocketAsyncEventArgs> wrappedHandler = null; wrappedHandler = (_, args) => { Assert.Equal(SocketError.Success, args.SocketError); args.RemoteEndPoint = null; args.Completed -= wrappedHandler; handler(); }; eventArgs.RemoteEndPoint = remoteEndpoint; eventArgs.Completed += wrappedHandler; if (!socket.ConnectAsync(eventArgs)) { wrappedHandler(null, eventArgs); } }
public static void ConnectWithTimeout(this TcpClient client, string host, int port, TimeSpan timeout) { var connectTask = client.ConnectAsync(host, port); if (!connectTask.Wait(timeout)) { try { ((IDisposable)client).Dispose(); } catch (SocketException) { } catch (ObjectDisposedException) { } throw new HalibutClientException("The client was unable to establish the initial connection within " + HalibutLimits.TcpClientConnectTimeout); } // unwrap the connect task to throw any connection exceptions connectTask.GetAwaiter().GetResult(); }
public static Task ConnectAsync(this Socket socket, IPEndPoint endPoint) { var tcs = new TaskCompletionSource<object>(); var ea = new SocketAsyncEventArgs { RemoteEndPoint = endPoint }; EventHandler<SocketAsyncEventArgs> completedHandler = null; completedHandler = (sender, args) => { switch (args.SocketError) { case SocketError.ConnectionAborted: case SocketError.OperationAborted: tcs.TrySetCanceled(); break; case SocketError.Success: tcs.TrySetResult(string.Empty); break; default: tcs.TrySetException(new SocketException((int)args.SocketError)); break; } ea.Completed -= completedHandler; }; ea.Completed += completedHandler; socket.ConnectAsync(ea); return tcs.Task; }
// // Summary: // Begins an asynchronous request for a remote host connection. // // Parameters: // remoteEP: // An System.Net.EndPoint that represents the remote host. // // callback: // The System.AsyncCallback delegate. // // state: // An object that contains state information for this request. // // Returns: // An System.IAsyncResult that references the asynchronous connection. // // Exceptions: // T:System.ArgumentNullException: // remoteEP is null. // // T:System.Net.Sockets.SocketException: // An error occurred when attempting to access the socket. See the Remarks section // for more information. // // T:System.ObjectDisposedException: // The System.Net.Sockets.Socket has been closed. // // T:System.Security.SecurityException: // A caller higher in the call stack does not have permission for the requested // operation. // // T:System.InvalidOperationException: // The System.Net.Sockets.Socket is System.Net.Sockets.Socket.Listen(System.Int32)ing. public static IAsyncResult BeginConnect(this Socket socket, EndPoint remoteEP, AsyncCallback callback, object state) { return TaskToApm.Begin(socket.ConnectAsync(remoteEP), callback, state); }
// // Summary: // Begins an asynchronous request for a remote host connection. The host is specified // by a host name and a port number. // // Parameters: // host: // The name of the remote host. // // port: // The port number of the remote host. // // requestCallback: // An System.AsyncCallback delegate that references the method to invoke when the // connect operation is complete. // // state: // A user-defined object that contains information about the connect operation. // This object is passed to the requestCallback delegate when the operation is complete. // // Returns: // An System.IAsyncResult that references the asynchronous connection. // // Exceptions: // T:System.ArgumentNullException: // host is null. // // T:System.ObjectDisposedException: // The System.Net.Sockets.Socket has been closed. // // T:System.NotSupportedException: // This method is valid for sockets in the System.Net.Sockets.AddressFamily.InterNetwork // or System.Net.Sockets.AddressFamily.InterNetworkV6 families. // // T:System.ArgumentOutOfRangeException: // The port number is not valid. // // T:System.InvalidOperationException: // The System.Net.Sockets.Socket is System.Net.Sockets.Socket.Listen(System.Int32)ing. public static IAsyncResult BeginConnect(this Socket socket, string host, int port, AsyncCallback requestCallback, object state) { return TaskToApm.Begin(socket.ConnectAsync(host, port), requestCallback, state); }
// // Summary: // Begins an asynchronous request for a remote host connection. The host is specified // by an System.Net.IPAddress array and a port number. // // Parameters: // addresses: // At least one System.Net.IPAddress, designating the remote host. // // port: // The port number of the remote host. // // requestCallback: // An System.AsyncCallback delegate that references the method to invoke when the // connect operation is complete. // // state: // A user-defined object that contains information about the connect operation. // This object is passed to the requestCallback delegate when the operation is complete. // // Returns: // An System.IAsyncResult that references the asynchronous connections. // // Exceptions: // T:System.ArgumentNullException: // addresses is null. // // T:System.Net.Sockets.SocketException: // An error occurred when attempting to access the socket. See the Remarks section // for more information. // // T:System.ObjectDisposedException: // The System.Net.Sockets.Socket has been closed. // // T:System.NotSupportedException: // This method is valid for sockets that use System.Net.Sockets.AddressFamily.InterNetwork // or System.Net.Sockets.AddressFamily.InterNetworkV6. // // T:System.ArgumentOutOfRangeException: // The port number is not valid. // // T:System.ArgumentException: // The length of address is zero. // // T:System.InvalidOperationException: // The System.Net.Sockets.Socket is System.Net.Sockets.Socket.Listen(System.Int32)ing. public static IAsyncResult BeginConnect(this Socket socket, IPAddress[] addresses, int port, AsyncCallback requestCallback, object state) { return TaskToApm.Begin(socket.ConnectAsync(addresses, port), requestCallback, state); }
public static void Connect(this IEventStoreConnection con) { var task = con.ConnectAsync(); task.Wait(); }
public static async Task<ConnectionState> ConnectTaskAsync(this IBandClient client) { return (ConnectionState)await client.ConnectAsync().AsTask(); }
public static Task<bool> ConnectAsync(this BitcoinChartsClient client) { return client.ConnectAsync(x => x .Address("api.bitcoincharts.com") .Port(27007) ); }
public static async Task ConnectAsync(this TcpClient client, IPEndPoint ipEndPoint) { await client.ConnectAsync(ipEndPoint.Address, ipEndPoint.Port); }
// // Summary: // Begins an asynchronous request for a remote host connection. The remote host // is specified by an System.Net.IPAddress and a port number (System.Int32). // // Parameters: // address: // The System.Net.IPAddress of the remote host. // // port: // The port number of the remote host. // // requestCallback: // An System.AsyncCallback delegate that references the method to invoke when the // operation is complete. // // state: // A user-defined object that contains information about the connect operation. // This object is passed to the requestCallback delegate when the operation is complete. // // Returns: // An System.IAsyncResult object that references the asynchronous connection. // // Exceptions: // T:System.ArgumentNullException: // The address parameter is null. // // T:System.Net.Sockets.SocketException: // An error occurred when attempting to access the socket. See the Remarks section // for more information. // // T:System.ObjectDisposedException: // The System.Net.Sockets.Socket has been closed. // // T:System.Security.SecurityException: // A caller higher in the call stack does not have permission for the requested // operation. // // T:System.ArgumentOutOfRangeException: // The port number is not valid. public static IAsyncResult BeginConnect(this TcpClient client, IPAddress address, int port, AsyncCallback requestCallback, object state) { return TaskToApm.Begin(client.ConnectAsync(address, port), requestCallback, state); }
public static void ConnectAsync(this Socket socket, ServerAsyncEventArgs e, ServerAsyncEventArgs.CompletedEventHandler handler) { e.Completed = handler; if (socket.ConnectAsync(e) == false) e.OnCompleted(socket); }