Connect() 공개 메소드

public Connect ( ) : void
리턴 void
예제 #1
0
        private static Client CreatedConnectedClient()
        {
            var client = new TcpSocket();

            client.Connect(ServerAddress, serverPort);
            return(client);
        }
예제 #2
0
        public void TestEvent()
        {
            bool isOnConnecting   = false;
            bool isOnConnected    = false;
            bool isOnDisconnected = false;
            bool isOnSend         = false;
            bool isOnReceive      = false;

            TcpSocket tcp = new TcpSocket();

            tcp.OnConnecting   += () => { isOnConnecting = true; };
            tcp.OnConnected    += () => { isOnConnected = true; };
            tcp.OnDisconnected += () => { isOnDisconnected = true; };
            tcp.OnSendBytes    += (x) => { isOnSend = true; };
            tcp.OnReceiveBytes += (x) => { isOnReceive = true; };

            tcp.Connect(Common.GetIpEndPoint());
            Assert.IsTrue(isOnConnecting);

            Common.WaitTrue(ref isOnConnected);
            Assert.IsTrue(isOnConnected);

            tcp.Send(new byte[10]);
            Common.WaitTrue(ref isOnSend);
            Assert.IsTrue(isOnSend);

            Common.WaitTrue(ref isOnReceive);
            Assert.IsTrue(isOnReceive);

            tcp.Disconnect();
            Assert.IsTrue(isOnDisconnected);
        }
예제 #3
0
        public async Task ShouldTriggerConnectionSentWhenSentSomeBytes()
        {
            NetworkDirection       direction = NetworkDirection.Outgoing;
            NetworkOutgoingMessage message   = new RandomMessage(113);

            using (NetworkFixture fixture = new NetworkFixture())
                using (TcpSocket host = fixture.Pool.New())
                    using (TcpSocket socket = fixture.Pool.New())
                    {
                        TcpSocketInfo info     = host.BindAndInfo();
                        int           port     = info.Endpoint.Port;
                        IPEndPoint    endpoint = new IPEndPoint(IPAddress.Loopback, port);

                        socket.Bind();
                        host.Listen(10);
                        host.Accept(null);

                        await socket.Connect(endpoint);

                        NetworkConnection connection = fixture.Pool.Create(socket, direction, endpoint);
                        Trigger           handler    = Trigger.Bind(ref fixture.Hooks.OnConnectionSent, data =>
                        {
                            data.Remote.Should().Be(NetworkAddress.Parse(endpoint));
                            data.Connection.Should().Be(connection);
                            data.Bytes.Should().Be(message.Length);
                        });

                        connection.Send(message);
                        handler.Wait().Should().BeTrue();
                    }
        }
예제 #4
0
 public void TcpStart()
 {
     //enabled = true;
     tcpClient = new TcpSocket();
     tcpClient.Connect(curHost.host, curHost.portTcp);
     tcpRuning = true;
 }
예제 #5
0
        public async Task <LoopSession> Start()
        {
            int?port;

            ReceiverService loop =
                new ReceiverBuilder()
                .WithDefinition(new LoopMessages())
                .Build(hooks);

            TcpSocket client = pool.New();
            TcpSocket server = pool.New();

            client.Bind();
            server.Bind(out port);
            server.Listen(1);

            IPEndPoint             endpoint = new IPEndPoint(IPAddress.Loopback, port.Value);
            Task <TcpSocketAccept> accept   = server.Accept();

            client.Connect(endpoint, null);

            PeerHash          peer     = PeerHash.Random();
            TcpSocketAccept   accepted = await accept;
            NetworkConnection receiver = pool.Create(accepted.Connection, NetworkDirection.Incoming, accepted.GetRemote());

            loop.StartProcessing(peer, receiver);
            return(new LoopSession(client, loop));
        }
예제 #6
0
        public void StartReceive(IPAddress Address, int Port, string FilePath)
        {
            // store destination path
            _filePath = FilePath;
            // initialize the file socket
            _clientSocket = new TcpSocket();
            // use the FileDataReceived callback
            _clientSocket.DataReceived += new TcpSocket.DataReceivedDelegate(OnDataReceived);
            _clientSocket.Connected    += new TcpSocket.ConnectedDelegate(OnConnected);
            _clientSocket.DisConnected += new TcpSocket.DisConnectedDelegate(OnDisConnected);
            _clientSocket.Connect(Address, Port);

            if (!_clientSocket.IsConnected)
            {
                // connect attempt failed
                throw new CryptoSocketException("DtmFileTransfer:StartReceive", "Could not connect to the remote host!", new SocketException((int)SocketError.ConnectionAborted));
            }
            else
            {
                // create the temp file  note: is WriteThrough more secure here?
                _tempPath = Path.Combine(Path.GetDirectoryName(_filePath), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".tmp");
                using (new FileStream(_tempPath, FileMode.Create, FileAccess.Write, FileShare.Read)) { }
                // set to hidden to avoid cross process errors
                File.SetAttributes(_tempPath, File.GetAttributes(_tempPath) | FileAttributes.Hidden);
                _clientSocket.ReceiveBufferSize = m_bufferSize;
                _clientSocket.SendBufferSize    = m_bufferSize;
                // start receiving
                _clientSocket.ReceiveAsync();
                _clientSocket.ReceiveTimeout = -1;
                // connection established
                _isConnected = true;
            }
        }
예제 #7
0
        public void PauseShouldPreventNewConnections()
        {
            ServerHelper.EchoServer((server, port, sync) =>
            {
                server.Pause(5000); // prevent connections for 5 seconds

                Assert.IsTrue(server.IsPaused, "Server should be paused");
                var socket = new TcpSocket(TcpSocketType.IPv4);
                socket.Data += (data, count) => Assert.Fail("We should never receive data");
                socket.Connect(port, connectedCallback: self =>
                {
                    Assert.IsTrue(server.IsPaused, "Server should be paused");
                    self.Write("test");

                    Thread.Sleep(2000);
                    Assert.IsFalse(self.IsConnected);

                    sync.SignalAndWait();
                });

                Thread.Sleep(10000);

                Assert.IsFalse(server.IsPaused, "Server should be unpaused");

                //accepting connections
                socket = new TcpSocket(TcpSocketType.IPv4);
                socket.Connect(port, connectedCallback: self =>
                {
                    Assert.IsTrue(self.IsConnected);

                    sync.SignalAndWait();
                });
            }, 3);
        }
예제 #8
0
파일: SendTests.cs 프로젝트: vnvizitiu/leak
        public void CanSendDataUsingCallbackToExampleSite()
        {
            TimeSpan         timeout = TimeSpan.FromSeconds(2);
            ManualResetEvent check   = new ManualResetEvent(false);

            IPAddress[] addresses = Dns.GetHostAddresses("www.example.com");
            IPEndPoint  endpoint  = new IPEndPoint(addresses[0], 80);

            using (CompletionThread worker = new CompletionThread())
            {
                SocketFactory factory = new SocketFactory(worker);
                TcpSocket     socket  = factory.Tcp();

                socket.Bind();
                worker.Start();

                TcpSocketSendCallback onSent = result =>
                {
                    check.Set();
                };

                TcpSocketConnectCallback onConnected = result =>
                {
                    string request = "GET /index.html HTTP/1.1\r\nHost: www.example.com\r\n\r\n";
                    byte[] data    = Encoding.ASCII.GetBytes(request);

                    socket.Send(data, onSent);
                };

                socket.Connect(endpoint, onConnected);
                bool completed = check.WaitOne(timeout);

                Assert.That(completed, Is.True);
            }
        }
예제 #9
0
        public async Task <string> Send(IPEndPoint endpoint, string message)
        {
            int progress = 0;

            byte[] output = new byte[message.Length];
            byte[] bytes  = Encoding.ASCII.GetBytes(message);

            using (TcpSocket socket = factory.Tcp())
            {
                socket.Bind();

                TcpSocketConnect connected = await socket.Connect(endpoint);

                TcpSocketSend sent = await socket.Send(bytes);

                while (progress < output.Length)
                {
                    SocketBuffer     buffer   = new SocketBuffer(output, progress);
                    TcpSocketReceive received = await socket.Receive(buffer);

                    if (received.Count == 0)
                    {
                        break;
                    }

                    progress += received.Count;
                }
            }

            return(Encoding.ASCII.GetString(output));
        }
예제 #10
0
파일: SendTests.cs 프로젝트: vnvizitiu/leak
        public async Task CanHandleTerminatedStream()
        {
            IPAddress  localhost = IPAddress.Loopback;
            IPEndPoint endpoint  = new IPEndPoint(localhost, 1234);

            using (CompletionThread worker = new CompletionThread())
            {
                SocketFactory factory = new SocketFactory(worker);

                using (TcpSocket server = factory.Tcp())
                    using (TcpSocket socket = factory.Tcp())
                    {
                        socket.Bind();
                        worker.Start();

                        server.Bind(endpoint.Port);
                        server.Listen(1);

                        Task <TcpSocketAccept> acceptable = server.Accept();
                        await socket.Connect(endpoint);

                        TcpSocketAccept accepted = await acceptable;
                        accepted.Connection.Dispose();

                        byte[]        buffer = new byte[10];
                        TcpSocketSend sent   = await socket.Send(buffer);

                        Assert.That(sent.Status, Is.EqualTo(SocketStatus.OK));
                    }
            }
        }
예제 #11
0
        public async Task CanReceiveDataUsingTasksToHostedEchoServer()
        {
            string request = "GET /index.html HTTP/1.1\r\nHost: www.example.com\r\n\r\n";

            byte[] input  = Encoding.ASCII.GetBytes(request);
            byte[] output = new byte[input.Length];

            using (CompletionThread worker = new CompletionThread())
            {
                SocketFactory factory = new SocketFactory(worker);
                TcpSocket     socket  = factory.Tcp();

                using (EchoServer server = new EchoServer(factory))
                {
                    socket.Bind();
                    worker.Start();
                    server.Start();

                    await socket.Connect(server.Endpoint);

                    await socket.Send(input);

                    await socket.Receive(output);

                    Assert.That(input, Is.EqualTo(output));
                }
            }
        }
예제 #12
0
    IEnumerator ConnectInternal(bool useDelay)
    {
        if (useDelay)
        {
            yield return(new WaitForSeconds(5f));           // немного ждём, полезно для реконнекта
        }

        if (startConnect)
        {
            yield break;
        }

        startConnect = true;

        if (socket == null)
        {
            socket = new TcpSocket();
            socket.OnMessageReceived += OnMessageReceived;
            socket.OnError           += OnErrorReceived;
        }


        var connectInfo = ChatSettings.Me;

        socket.Connect(connectInfo.Host, connectInfo.Port);
        textEntering.gameObject.SetActive(true);
        buttonConnect.gameObject.SetActive(false);
        //chatTitle.gameObject.SetActive(false);

        startConnect = false;
        ++connectCounter;
        yield break;
    }
예제 #13
0
        public async Task CanObtainAcceptedRemoteEndpointUsingTasks()
        {
            using (CompletionThread worker = new CompletionThread())
            {
                IPEndPoint    endpoint;
                SocketFactory factory = new SocketFactory(worker);

                using (TcpSocket server = factory.Tcp())
                    using (TcpSocket client = factory.Tcp())
                    {
                        worker.Start();
                        client.Bind();

                        server.Bind(IPAddress.Loopback);
                        server.Listen(1);

                        endpoint = server.Info().Endpoint;

                        Task <TcpSocketAccept> accepting = server.Accept();
                        await client.Connect(endpoint);

                        TcpSocketAccept accepted = await accepting;
                        IPEndPoint      remote   = accepted.GetRemote();

                        Assert.That(remote.Address, Is.EqualTo(endpoint.Address));
                        Assert.That(remote.Port, Is.Not.EqualTo(endpoint.Port));
                        Assert.That(remote.Port, Is.Not.Zero);
                    }
            }
        }
예제 #14
0
        public void Connect(Connection connection, Address address, bool noVerification)
        {
            TcpSocket socket = new TcpSocket();

            if (connection.Handler != null && connection.Handler.CanHandle(EventId.SocketConnect))
            {
                connection.Handler.Handle(Event.Create(EventId.SocketConnect, connection, null, null, socket));
            }

            socket.Connect(address.Host, address.Port);

            if (address.UseSsl)
            {
                SslSocket sslSocket = new SslSocket(socket, noVerification);
                if (connection.Handler != null && connection.Handler.CanHandle(Handler.EventId.SocketConnect))
                {
                    connection.Handler.Handle(Event.Create(EventId.SslAuthenticate, connection, null, null, sslSocket));
                }
                else
                {
                    sslSocket.AuthenticateAsClient(address.Host);
                }

                this.socketTransport = sslSocket;
            }
            else
            {
                this.socketTransport = socket;
            }
        }
예제 #15
0
 public void ConnectToUnknownHostShouldTimeOut()
 {
     using (var client = new TcpSocket())
     {
         bool isTimedOut = false;
         client.Connect(ServerAddress, 12345, () => isTimedOut = true);
         Assert.IsFalse(isTimedOut);
         Thread.Sleep((int)((client.Timeout + 0.5f) * 1000));
         Assert.IsTrue(isTimedOut);
     }
 }
예제 #16
0
    public void Connect(string strIpAddress, int port)
    {
        m_IpAddress = strIpAddress;
        m_Port      = port;

        mClientSocket = new TcpSocket <XPacket>();

        mClientSocket.Connect(m_IpAddress, m_Port, OnConnectedCallback, HandleReceiveData);

        Debug.Log("Net# Connect to " + strIpAddress + ": " + port);
    }
예제 #17
0
 static public int Connect(IntPtr l)
 {
     try {
         TcpSocket self = (TcpSocket)checkSelf(l);
         self.Connect();
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
예제 #18
0
        public void Execute(PeerConnectorContext context)
        {
            TcpSocket socket = context.Dependencies.Network.New();

            IPAddress[] addresses = Dns.GetHostAddresses(remote.Host);

            IPAddress  address  = addresses[0].MapToIPv4();
            IPEndPoint endpoint = new IPEndPoint(address, remote.Port);

            socket.Bind();
            socket.Connect(endpoint, data => OnConnected(context, data));
        }
예제 #19
0
        public void ClientThread(object context)
        {
            Main.gameMenu = true;
            Main.menuMode = 888;
            Main.MenuUI.SetState(new UINetworkConnection());
            object[]  parameter       = (object[])context;
            bool      exitThread      = false;
            DimPlayer player          = (DimPlayer)parameter[0];
            int       numberOfAttempt = 0;

            RemoteAddress adress = new TcpAddress(Netplay.ServerIP, 7776);

            ClientLoopSetup(adress);
            ISocket secondarySocket = new TcpSocket();

            secondarySocket.Connect(new TcpAddress(Netplay.ServerIP, 7776));

            while (!exitThread)
            {
                try
                {
                    Thread.Sleep(2500);
                    if (secondarySocket.IsDataAvailable())
                    {
                        byte[] data = new byte[ushort.MaxValue];
                        secondarySocket.AsyncReceive(data, 0, ushort.MaxValue, new SocketReceiveCallback(Netplay.Connection.ClientReadCallBack), null);
                        using (MemoryStream stream = new MemoryStream(data))
                        {
                            BinaryReader reader = new BinaryReader(new MemoryStream(data));
                        }
                        numberOfAttempt++;
                    }
                    else
                    {
                        byte[] data = new byte[ushort.MaxValue];
                        using (MemoryStream stream = new MemoryStream(data))
                        {
                            BinaryWriter writer = new BinaryWriter(stream);
                            writer.Write("hey");
                            secondarySocket.AsyncSend(writer.BaseStream.ReadAllBytes(), 0, ushort.MaxValue, new SocketSendCallback(Netplay.Connection.ClientWriteCallBack), null);
                        }
                    }
                }
                catch (Exception e)
                {
                    LogManager.GetLogger("Second thread").Error(e.Message, e);
                }
            }
            Netplay.Connection.Socket.Close();
            Netplay.StartTcpClient();
            player.inTransit = false;
        }
예제 #20
0
        public void Connect(Connection connection, Address address, bool noVerification)
        {
            var ipHostEntry = Dns.GetHostEntry(address.Host);
            Exception exception = null;
            TcpSocket socket = null;

            foreach (var ipAddress in ipHostEntry.AddressList)
            {
                if (ipAddress == null)
                {
                    continue;
                }

                try
                {
                    socket = new TcpSocket();
                    socket.Connect(new IPEndPoint(ipAddress, address.Port));
                    exception = null;
                    break;
                }
                catch (SocketException socketException)
                {
                    if (socket != null)
                    {
                        socket.Close();
                        socket = null;
                    }

                    exception = socketException;
                }
            }

            if (exception != null)
            {
                throw exception;
            }

            if (address.UseSsl)
            {
                SslSocket sslSocket = new SslSocket(socket);
                sslSocket.AuthenticateAsClient(
                    address.Host,
                    null,
                    noVerification ? SslVerification.NoVerification : SslVerification.VerifyPeer,
                    SslProtocols.Default);
                this.socketTransport = sslSocket;
            }
            else
            {
                this.socketTransport = socket;
            }
        }
예제 #21
0
        public void Connect(Connection connection, Address address, bool noVerification)
        {
            var       ipHostEntry = Dns.GetHostEntry(address.Host);
            Exception exception   = null;
            TcpSocket socket      = null;

            foreach (var ipAddress in ipHostEntry.AddressList)
            {
                if (ipAddress == null)
                {
                    continue;
                }

                try
                {
                    socket = new TcpSocket();
                    socket.Connect(new IPEndPoint(ipAddress, address.Port));
                    exception = null;
                    break;
                }
                catch (SocketException socketException)
                {
                    if (socket != null)
                    {
                        socket.Close();
                        socket = null;
                    }

                    exception = socketException;
                }
            }

            if (exception != null)
            {
                throw exception;
            }

            if (address.UseSsl)
            {
                SslSocket sslSocket = new SslSocket(socket);
                sslSocket.AuthenticateAsClient(
                    address.Host,
                    null,
                    noVerification ? SslVerification.NoVerification : SslVerification.VerifyPeer,
                    SslProtocols.Default);
                this.socketTransport = sslSocket;
            }
            else
            {
                this.socketTransport = socket;
            }
        }
예제 #22
0
        static void Main(string[] args)
        {
            Console.WriteLine("[Client]");

            try
            {
                dora.Connect("127.0.0.1", 9999);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            Console.ReadLine();
        }
예제 #23
0
        public void TestConnect()
        {
            TcpSocket tcp = new TcpSocket();

            tcp.Connect(Common.GetIpEndPoint());

            //Test connected
            Common.WaitConnected(tcp);
            Assert.IsTrue(tcp.IsConnected);

            //Test disconnect
            tcp.Disconnect();
            Assert.IsFalse(tcp.IsConnected);
        }
예제 #24
0
        private void OnSent(TcpSocketSend data)
        {
            if (data.Status == SocketStatus.OK)
            {
                outgoing = new SocketBuffer(data.Buffer.Data, data.Buffer.Offset + data.Count, data.Buffer.Count - data.Count);

                if (incoming.Count > 0)
                {
                    socket.Receive(incoming, OnReceived);
                }
                else if (outgoing.Count > 0)
                {
                    socket.Send(outgoing, OnSent);
                }
                else
                {
                    incoming = new SocketBuffer(incoming.Data);
                    outgoing = new SocketBuffer(outgoing.Data);

                    if (session.Elapsed > TimeSpan.FromMinutes(1))
                    {
                        socket  = factory.Tcp();
                        session = Stopwatch.StartNew();

                        socket.Bind();
                        socket.Connect(endpoint, OnConnected);
                        data.Socket.Dispose();
                    }
                    else
                    {
                        socket.Send(outgoing, OnSent);
                    }
                }
            }
            else
            {
                Console.WriteLine("OnSent");
                socket.Dispose();
            }

            counter += data.Count;

            if (counter - previous > 1024 * 1024 * 1024)
            {
                previous = counter;

                Console.WriteLine($"{counter}: {counter / watch.ElapsedMilliseconds}");
            }
        }
예제 #25
0
        public void ReconnectTest()
        {
            TcpSocket socket = new TcpSocket();

            Assert.IsFalse(socket.Connected);

            socket.Connect(new DnsEndPoint("www.google.com", 80));
            Assert.IsTrue(socket.Connected);

            socket.Dispose();
            Assert.IsFalse(socket.Connected);

            socket.Reconnect();
            Assert.IsTrue(socket.Connected);
        }
예제 #26
0
        public async Task CanHandleNotBoundSocket()
        {
            using (CompletionThread worker = new CompletionThread())
            {
                SocketFactory factory = new SocketFactory(worker);

                using (TcpSocket socket = factory.Tcp())
                {
                    IPEndPoint       endpoint  = new IPEndPoint(IPAddress.Loopback, 80);
                    TcpSocketConnect connected = await socket.Connect(endpoint);

                    Assert.That(connected.Status, Is.Not.EqualTo(SocketStatus.OK));
                }
            }
        }
        public void ExceptionTest()
        {
            AutoResetEvent evt           = new AutoResetEvent(false);
            Exception      testException = null;
            var            tcp           = new TcpSocket();

            tcp.OnException += (e) =>
            {
                testException = e;
                evt.Set();
            };
            tcp.Connect("123", 999);
            evt.WaitOne();
            Assert.IsNotNull(testException);
        }
예제 #28
0
        public void Start()
        {
            if (this.isConnecting)
            {
                return;
            }

            TcpSocket tcpSocket = new TcpSocket(settings.MasterServerIP, settings.MasterServerPort);

            tcpSocket.Connect();
            this.MasterServer = new MasterServer(tcpSocket, this.masterServerPacketProcessor);
            this.MasterServer.TcpSocketWorker.Run();

            this.isConnecting = true;
        }
예제 #29
0
        public void Connect(Connection connection, Address address, bool noVerification)
        {
            TcpSocket socket = new TcpSocket();
            socket.Connect(address.Host, address.Port);

            if (address.UseSsl)
            {
                SslSocket sslSocket = new SslSocket(socket, noVerification);
                sslSocket.AuthenticateAsClient(address.Host);
                this.socketTransport = sslSocket;
            }
            else
            {
                this.socketTransport = socket;
            }
        }
예제 #30
0
        public void TestSendReceive()
        {
            TcpSocket tcp = new TcpSocket();

            tcp.Connect(Common.GetIpEndPoint());
            Common.WaitConnect(tcp);
            int length = 0;

            tcp.OnSocketReceive += (x) =>
            {
                length = x.Length;
            };
            tcp.Send(new byte[10]);
            Common.WaitValue(ref length, 10);
            Assert.AreEqual(length, 10);
        }
예제 #31
0
        public void Connect(Connection connection, Address address, bool noVerification)
        {
            TcpSocket socket = new TcpSocket();

            socket.Connect(address.Host, address.Port);

            if (address.UseSsl)
            {
                SslSocket sslSocket = new SslSocket(socket, noVerification);
                sslSocket.AuthenticateAsClient(address.Host);
                this.socketTransport = sslSocket;
            }
            else
            {
                this.socketTransport = socket;
            }
        }
예제 #32
0
        public void ServerRemovesStaleConnections()
        {
            ServerHelper.Server((server, port, sync) =>
            {
                var socket = new TcpSocket(TcpSocketType.IPv4);
                socket.Connect(port, connectedCallback: self =>
                {
                    Thread.Sleep(500);
                    Assert.AreEqual(1, server.ConnectionCount, "we are connected");
                    self.Dispose();
                    Thread.Sleep(500);
                    Assert.AreEqual(0, server.ConnectionCount, "no connections now");

                    sync.SignalAndWait();
                });
            }, timeout: 30);
        }
예제 #33
0
        public void TestLargeMessage()
        {
            var tcp = new TcpSocket();

            tcp.Connect(Common.GetIpEndPoint());
            Common.WaitConnected(tcp);
            int length = 0;

            tcp.OnSocketReceive += (x) =>
            {
                length += x.Length;
            };
            tcp.Send(new byte[1 << 10]);
            Common.WaitValue(ref length, 1 << 10, 10000);
            tcp.DisConnect();
            Console.WriteLine(length);
            Assert.AreEqual(length, 1 << 10);
        }
예제 #34
0
        public void TestEvent()
        {
            var  tcp          = new TcpSocket();
            bool isConnecting = false;

            tcp.OnConnecting += () => { isConnecting = true; };
            bool isConnected = false;

            tcp.OnConnected += () => { isConnected = true; };
            bool isDisconnected = false;

            tcp.OnDisconnected += () => { isDisconnected = true; };
            tcp.Connect(Common.GetIpEndPoint());
            Common.WaitConnect(tcp);
            tcp.DisConnect();
            Assert.IsTrue(isConnecting);
            Assert.IsTrue(isConnected);
            Assert.IsTrue(isDisconnected);
        }
예제 #35
0
        public void Connect(Connection connection, Address address, bool noVerification)
        {
            var ipHostEntry = Dns.GetHostEntry(address.Host);
            Exception exception = null;
            TcpSocket socket = null;
            // reference to SSL socket, wrapper for above TCP socket
            SslSocket sslSocket = null;

            foreach (var ipAddress in ipHostEntry.AddressList)
            {
                if (ipAddress == null)
                {
                    continue;
                }

                try
                {
                    socket = new TcpSocket();
                    // SSL connection requested with an SSL host
                    if (address.UseSsl)
                    {
                        // wrap TCP socket to SSL socket
                        sslSocket = new SslSocket(socket, address.Host, ValidateCertificate);
                    }
                    socket.Connect(new IPEndPoint(ipAddress, address.Port));
                    exception = null;
                    break;
                }
                catch (SocketException socketException)
                {
                    if (address.UseSsl)
                    {
                        if (sslSocket != null)
                        {
                            sslSocket.Close();
                            sslSocket = null;
                        }
                    }

                    if (socket != null)
                    {
                        socket.Close();
                        socket = null;
                    }

                    exception = socketException;
                }
            }

            if (exception != null)
            {
                throw exception;
            }

            if (address.UseSsl)
            {
                this.socketTransport = sslSocket;
            }
            else
            {
                this.socketTransport = socket;
            }
        }