Exemple #1
0
        /// <summary>
        /// Open a new or existing socket as a client
        /// </summary>
        public static async Task <SocketConnection> ConnectAsync(
            EndPoint endpoint,
            PipeOptions sendPipeOptions,
            PipeOptions receivePipeOptions,
            SocketConnectionOptions connectionOptions = SocketConnectionOptions.None,
            Func <SocketConnection, Task> onConnected = null,
            Socket socket  = null,
            string name    = null,
            ILogger logger = null)
        {
            var addressFamily = endpoint.AddressFamily == AddressFamily.Unspecified ?
                                AddressFamily.InterNetwork : endpoint.AddressFamily;
            var protocolType = addressFamily == AddressFamily.Unix ?
                               ProtocolType.Unspecified : ProtocolType.Tcp;

            if (socket == null)
            {
                socket = new Socket(addressFamily, SocketType.Stream, protocolType);
            }
            if (sendPipeOptions == null)
            {
                sendPipeOptions = PipeOptions.Default;
            }
            if (receivePipeOptions == null)
            {
                receivePipeOptions = PipeOptions.Default;
            }

            SetRecommendedClientOptions(socket);

            logger = logger ?? NullLoggerFactory.Instance.CreateLogger("NetGear.Core.SocketConnection");
            using (var args = new SocketAwaitableEventArgs((connectionOptions & SocketConnectionOptions.InlineConnect) == 0 ? PipeScheduler.ThreadPool : null))
            {
                args.RemoteEndPoint = endpoint;
                _logger.LogVerbose(name, $"connecting to {endpoint}...");

                if (!socket.ConnectAsync(args))
                {
                    args.Complete();
                }
                await args;
            }

            _logger.LogVerbose(name, "connected");

            var connection = Create(socket, sendPipeOptions, receivePipeOptions, connectionOptions, name, logger);

            if (onConnected != null)
            {
                await onConnected(connection).ConfigureAwait(false);
            }

            return(connection);
        }