Exemplo n.º 1
0
        protected Connection OpenConnection(IPEndPoint endpoint, Action <Connection> connectionInitializer)
        {
            Socket tmp = null;

            try
            {
                tmp = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                var asyncState = tmp.BeginConnect(endpoint, null, null);
                if (asyncState.AsyncWaitHandle.WaitOne(ConnectTimeout, true))
                {
                    tmp.EndConnect(asyncState); // checks for exception
                    var conn = ProtocolFactory.CreateConnection(endpoint) ?? new Connection();

                    connectionInitializer?.Invoke(conn);

                    conn.Socket = tmp;
                    var processor = ProtocolFactory.GetProcessor();
                    conn.SetProtocol(processor);
                    processor.InitializeOutbound(Context, conn);
                    StartReading(conn);
                    conn.InitializeClientHandshake(Context);
                    tmp = null;
                    return(conn);
                }
                else
                {
                    Close();
                    throw new TimeoutException("Unable to connect to endpoint");
                }
            }
            finally
            {
                ((IDisposable)tmp)?.Dispose();
            }
        }