Beispiel #1
0
        public void Connect(string address)
        {
            try
            {
                System.Net.Sockets.TcpClient tcp143 = new System.Net.Sockets.TcpClient();
                System.Net.Sockets.TcpClient tcp993 = new System.Net.Sockets.TcpClient();

                if (!tcp143.ConnectAsync(address, 143).Wait(1000))
                {
                    if (!tcp993.ConnectAsync(address, 993).Wait(1000))
                    {
                        throw new Exception("Connection timeout");
                    }
                    else
                    {
                        tcpc = tcp993;
                    }
                }
                else
                {
                    if (tcp143 != null)
                    {
                        tcpc = tcp143;
                        Read(true);
                        Write("CAPABILITIES");
                        if (Read(false).Contains("STARTTLS"))
                        {
                            Write("STARTTLS");
                        }
                        else
                        {
                            if (!tcp993.ConnectAsync(address, 993).Wait(1000))
                            {
                                throw new Exception("Connection not secure");
                            }
                            else
                            {
                                tcpc = tcp993;
                            }
                        }
                    }
                }

                ssl = new System.Net.Security.SslStream(tcpc.GetStream());
                ssl.AuthenticateAsClient(address);
                ssl.Flush();
                secure = true;
                Read(true);
            }
            catch (System.Net.Sockets.SocketException)
            {
                throw new Exception("Connection failed");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static async Task PerfLoopComparedAsync(int bufferSize, CancellationToken ct)
        {
            var port   = 5000;
            var cts    = new CancellationTokenSource();
            var server = PerfEchoServer(port, cts.Token);
            await Task.Delay(100);

            try {
                using (var client = new System.Net.Sockets.TcpClient()) {
                    await client.ConnectAsync(hostName, port);

                    var buffer = new byte[bufferSize];
                    _rand.NextBytes(buffer);
                    long _received  = 0;
                    var  _receivedw = Stopwatch.StartNew();
                    for (var i = 0; !ct.IsCancellationRequested; i++)
                    {
                        _received += await EchoLoopAsync2(client.GetStream(), buffer);

                        Console.CursorLeft = 0; Console.CursorTop = 0;
                        Console.Out.WriteLine($"{i} { (_received / _receivedw.ElapsedMilliseconds) } kB/sec");
                    }
                }
            }
            finally {
                cts.Cancel();
                await server;
            }
        }
Beispiel #3
0
        public async Task ConnectAsync(string host, int port)
        {
            if (_tcpClient != null && _tcpClient.Connected)
            {
                return; // already connected
            }
            OnConnectStatusChanged(TcpClientStatusEventArgs.EConnectStatus.Connecting);

            try
            {
                // resolve ip address
                IPAddress addr = await NetworkUtils.DnsResolveAsync(host);

                _tcpClient = new System.Net.Sockets.TcpClient(addr.AddressFamily);

                await _tcpClient.ConnectAsync(addr, port);

                OnConnectStatusChanged(TcpClientStatusEventArgs.EConnectStatus.Connected);

                StartReceive();
            }
            catch (Exception)
            {
                Disconnect();
                throw;
            }
        }
Beispiel #4
0
        public async void StartAsync()
        {
            System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(this.ipString);

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

            objSck = new System.Net.Sockets.TcpClient();
            // 小さいバッファを貯めない(遅延させない)
            objSck.NoDelay = true;
            try
            {
                await objSck.ConnectAsync(ipAdd, port);
            }
            catch (Exception)
            {
                //return false;
                return;
            }

            //NetworkStreamを取得
            ns = objSck.GetStream();

            ConnectResult = true;
            //return ConnectResult;
        }
Beispiel #5
0
        async void ConnectClient()
        {
            System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
            await client.ConnectAsync("192.168.1.142", 3070);

            Debug.WriteLine("connected");
        }
Beispiel #6
0
 public static async Task<OpcWriter> CreateAsync(IPEndPoint target)
 {
     var client = new System.Net.Sockets.TcpClient();
     await client.ConnectAsync(target.Address, target.Port).ConfigureAwait(false);
     var stream = client.GetStream();
     return new OpcWriter(stream, true);
 }
Beispiel #7
0
 public static async Task<OpcWriter> CreateAsync(string host, int port = DefaultPort)
 {
     var client = new System.Net.Sockets.TcpClient();
     await client.ConnectAsync(host, port).ConfigureAwait(false);
     var stream = client.GetStream();
     return new OpcWriter(stream, true);
 }
Beispiel #8
0
        private async Task <bool> PingHost(IPEndPoint target, Guid remote_session_id, CancellationToken cancel_token)
        {
            Logger.Debug("Ping requested. Try to ping: {0}({1})", target, remote_session_id);
            bool result = false;

            try {
                var client = new System.Net.Sockets.TcpClient(target.AddressFamily);
                client.ReceiveTimeout = 2000;
                client.SendTimeout    = 2000;
                await client.ConnectAsync(target.Address, target.Port).ConfigureAwait(false);

                var stream = client.GetStream();
                await stream.WriteAsync(new Atom(Atom.PCP_CONNECT, 1), cancel_token).ConfigureAwait(false);

                var helo = new AtomCollection();
                helo.SetHeloSessionID(PeerCast.SessionID);
                await stream.WriteAsync(new Atom(Atom.PCP_HELO, helo), cancel_token).ConfigureAwait(false);

                var res = await stream.ReadAtomAsync(cancel_token).ConfigureAwait(false);

                if (res.Name == Atom.PCP_OLEH)
                {
                    var session_id = res.Children.GetHeloSessionID();
                    if (session_id.HasValue && session_id.Value == remote_session_id)
                    {
                        Logger.Debug("Ping succeeded");
                        result = true;
                    }
                    else
                    {
                        Logger.Debug("Ping failed. Remote SessionID mismatched");
                    }
                }
                await stream.WriteAsync(new Atom(Atom.PCP_QUIT, Atom.PCP_ERROR_QUIT), cancel_token).ConfigureAwait(false);

                stream.Close();
                client.Close();
            }
            catch (InvalidDataException e) {
                Logger.Debug("Ping failed");
                Logger.Debug(e);
            }
            catch (System.Net.Sockets.SocketException e) {
                Logger.Debug("Ping failed");
                Logger.Debug(e);
            }
            catch (EndOfStreamException e) {
                Logger.Debug("Ping failed");
                Logger.Debug(e);
            }
            catch (System.IO.IOException io_error) {
                Logger.Debug("Ping failed");
                Logger.Debug(io_error);
                if (!(io_error.InnerException is System.Net.Sockets.SocketException))
                {
                    throw;
                }
            }
            return(result);
        }
Beispiel #9
0
        static void Main(string[] args)
        {
            //Initialize variables, connect tcp client
            IPAddress address;

            IPAddress.TryParse("127.0.0.1", out address);
            int port = 7777;

            client = new System.Net.Sockets.TcpClient();
            Task wait = client.ConnectAsync(address, port);

            wait.Wait();

            //client.Connect(endpoint);

            //Start tasks to run the writing messages to the stream, and the reading of messages from the stream
            Task writeTask = new Task(write);
            Task readTask  = new Task(read);

            gottenUser = false;

            writeTask.Start();
            readTask.Start();

            writeTask.Wait();
            readTask.Wait();
        }
Beispiel #10
0
        public static async Task <OpcWriter> CreateAsync(IPEndPoint target)
        {
            var client = new System.Net.Sockets.TcpClient();
            await client.ConnectAsync(target.Address, target.Port).ConfigureAwait(false);

            var stream = client.GetStream();

            return(new OpcWriter(stream, true));
        }
Beispiel #11
0
        public static async Task <OpcWriter> CreateAsync(string host, int port = DefaultPort)
        {
            var client = new System.Net.Sockets.TcpClient();
            await client.ConnectAsync(host, port).ConfigureAwait(false);

            var stream = client.GetStream();

            return(new OpcWriter(stream, true));
        }
Beispiel #12
0
        private async Task _Client_Disconnected(Exception arg)
        {
            using (System.Net.Sockets.TcpClient TCP = new System.Net.Sockets.TcpClient())
            {
                await TCP.ConnectAsync(System.Net.IPAddress.Parse("127.0.0.1"), 1212);

                var    stream = TCP.GetStream();
                byte[] data   = System.Text.Encoding.UTF8.GetBytes("restartme");
                stream.Write(data, 0, data.Length);
            }
        }
Beispiel #13
0
        public async Task ConnectAsync(string host, int port)
        {
            if (IsConnected)
            {
                throw new InvalidOperationException("Client is already started");
            }

            _client = new System.Net.Sockets.TcpClient();
            await _client.ConnectAsync(host, port);

            IsConnected = true;
            _stream     = _client.GetStream();
        }
        static async Task <System.Net.Sockets.TcpClient> CreateTcpClient(
            IPEndPoint endpoint,
            TcpClientConnectionHandler?connHandler = null
            )
        {
            if (connHandler != null)
            {
                return(await connHandler(endpoint));
            }

            var res = new System.Net.Sockets.TcpClient(endpoint.AddressFamily);
            await res.ConnectAsync(endpoint.Address, endpoint.Port);

            return(res);
        }
 public TcpClient(string ipAddr, int port)
 {
     Client = new System.Net.Sockets.TcpClient();
     CConsole.DarkGray("[TcpClient] Connecting");
     Client.ConnectAsync(ipAddr, port).Wait();
     if (!Client.Connected)
     {
         CConsole.Red("!!! Error Connecting TcpClient to port {0} !!!", port);
         throw new Exception("notConnected");
     }
     else
     {
         CConsole.DarkGray("[TcpClient] Connected");
         Stream = Client.GetStream();
     }
 }
Beispiel #16
0
        /// <summary>
        /// Initialises a new instance of the <see cref="TcpClient"/> class.
        /// </summary>
        /// <param name="hostName">The host name.</param>
        /// <param name="port">The port.</param>
        public TcpClient(string hostName, int port)
        {
#if NET451
            this.client = new System.Net.Sockets.TcpClient(hostName, port);
#else
            this.client = new System.Net.Sockets.TcpClient();
            // .NetStandard does not include a synchronous constructor or Connect method.
            // This will normally not be connected by the time the constructor returns,
            // it is the responsibility of the caller to ensure that they wait for the
            // connection to complete or fail, using this.Connected.
            // The PrimS.Telnet.Client constructor does this.
            // Adding something awaitable on this class to connect or wait for connection
            // would break backward compatibility and require a lot of refactoring.
            // This will do for now.
            var nowait = client.ConnectAsync(hostName, port);
#endif
        }
Beispiel #17
0
        private async Task <VideoInfo> GetVideoViaTCPAsync(string domain)
        {
            using (System.Net.Sockets.TcpClient TCP = new System.Net.Sockets.TcpClient())
            {
                await TCP.ConnectAsync(System.Net.IPAddress.Parse("127.0.0.1"), 1212);

                var    stream = TCP.GetStream();
                byte[] data   = System.Text.Encoding.UTF8.GetBytes(domain);
                stream.Write(data, 0, data.Length);
                string response = "";
                do
                {
                    System.Threading.Thread.Sleep(200);
                } while (stream.CanRead == false);
                using (System.IO.StreamReader SR = new System.IO.StreamReader(stream))
                {
                    response = SR.ReadToEnd();
                }
                VideoInfo VideoInfo = null;
                Newtonsoft.Json.Linq.JToken Vals = Newtonsoft.Json.Linq.JToken.Parse(response);
                if (Vals["errorset"] != null)
                {
                    SendMessage_Raised("Failed to get track: " + Vals.SelectToken("errorset").ToString(), MessageClient);
                }
                else
                {
                    string          url   = Vals.SelectToken("url").ToString();
                    string          title = Vals.SelectToken("title").ToString();
                    VideoInfo.Types type  = VideoInfo.Types.Video;
                    switch (Vals.SelectToken("type").ToString())
                    {
                    case "video":
                        type = VideoInfo.Types.Video;
                        break;

                    case "livestream":
                        type = VideoInfo.Types.Livestream;
                        break;
                    }
                    VideoInfo = VideoInfo.CreateCustomVideo(url, title, type);
                }
                return(VideoInfo);
            }
        }
Beispiel #18
0
        public async void Connect()
        {
            try
            {
                Client = new System.Net.Sockets.TcpClient(new IPEndPoint(IPAddress.Parse(IpAddressHelper.GetHostIp()), new Random().Next(80, 6000)));
                Env.Print($"connecting to {this.Ip}:{this.Port}");
                await Client.ConnectAsync(IPAddress.Parse(this.Ip), this.Port);

                Env.Print($"connected to {Client.Client.RemoteEndPoint} from {Client.Client.LocalEndPoint}");
                Session = new TcpClientSession(Client);
                NewSession(this, Session);
                Session.Disconnected += Disconnected;

                Connected?.Invoke(this, Session);
                Session.Receive();
            }
            catch (Exception ex)
            {
                Env.Print($"connect failed.cause:{ex.Message}");
                ConnectFailed(this, ex);
            }
        }
Beispiel #19
0
        } // End Sub Test1

        // https://stackoverflow.com/questions/28612289/tcpclient-connectasync-or-socket-beginconnect-with-non-blocking-timeout-setting
        public static void Test2()
        {
            IDnsSecResolver resolver = new DnsSecRecursiveDnsResolver();

            //using (System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient("example.com", 443))

            using (System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient())
            {
                System.Threading.Tasks.Task t = client.ConnectAsync("example.com", 443);
                t.Wait();

                using (ARSoft.Tools.Net.Net.DaneStream stream = new ARSoft.Tools.Net.Net.DaneStream(client.GetStream(), resolver))
                {
                    stream.AuthenticateAsClient("example.com", 443);

                    if (stream.IsAuthenticatedByDane)
                    {
                        System.Console.WriteLine("Stream is authenticated by DANE/TLSA");
                    }

                    // work with the stream
                } // End Using stream
            }     // End Using client
        }         // End Sub Test2
Beispiel #20
0
        private void Run()
        {
            Task.Run(async() =>
            {
                try
                {
                    using (_remoteClient)
                        using (client)
                        {
                            await client.ConnectAsync(_remoteServer.Address, _remoteServer.Port);
                            var serverStream = client.GetStream();
                            var remoteStream = _remoteClient.GetStream();

                            await Task.WhenAny(remoteStream.CopyToAsync(serverStream), serverStream.CopyToAsync(remoteStream));
                        }
                }
                catch (Exception) { }
                finally
                {
                    Console.WriteLine($"Closed {_clientEndpoint} => {_remoteServer}");
                    _remoteClient = null;
                }
            });
        }
Beispiel #21
0
        /// <summary>
        /// Sends the ZPL code to the specified Zebra printer
        /// </summary>
        /// <param name="printerIPAddress">The IP address to contact the printer</param>
        /// <param name="printerPort">The port to connect with the printer</param>
        /// <param name="zplString">Raw zpl string</param>
        /// <returns>A boolean indicatig true the sending has been executed successfully.  Otherwise it returns false.</returns>
        public async Task <bool> SendDataToPrinter(string printerIPAddress, int printerPort, string zplString)
        {
            try
            {
                using (System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient())
                {
                    await client.ConnectAsync(printerIPAddress, printerPort);

                    using (System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream()))
                    {
                        writer.Write(zplString); writer.Flush();

                        writer.Close();
                        client.Close();
                    }
                }

                return(true);
            }
            catch //(Exception ex)
            {
                throw;
            }
        }
Beispiel #22
0
        public bool Connect(string host, int port, string module, bool requirewrite = false)
        {
            if (port == -1)
                port = VersionrDefaultPort;
            IEnumerator<SharedNetwork.Protocol> protocols = SharedNetwork.AllowedProtocols.Cast<SharedNetwork.Protocol>().GetEnumerator();
            Retry:
            if (!protocols.MoveNext())
            {
                Printer.PrintMessage("#e#No valid protocols available.##");
                return false;
            }
            Host = host;
            Port = port;
            Module = module;
            Connected = false;
            try
            {
                Connection = new System.Net.Sockets.TcpClient();
                var connectionTask = Connection.ConnectAsync(Host, Port);
                if (!connectionTask.Wait(5000))
                {
                    throw new Exception(string.Format("Couldn't connect to target: {0}", this.VersionrURL));
                }
            }
            catch (Exception e)
            {
                Printer.PrintError(e.Message);
                return false;
            }
            if (Connection.Connected)
            {
                try
                {
                    Printer.PrintDiagnostics("Connected to server at {0}:{1}", host, port);
                    Handshake hs = Handshake.Create(protocols.Current);
                    hs.RequestedModule = Module;
                    Printer.PrintDiagnostics("Sending handshake...");
                    Connection.NoDelay = true;
                    ProtoBuf.Serializer.SerializeWithLengthPrefix<Handshake>(Connection.GetStream(), hs, ProtoBuf.PrefixStyle.Fixed32);

                    var startTransaction = ProtoBuf.Serializer.DeserializeWithLengthPrefix<Network.StartTransaction>(Connection.GetStream(), ProtoBuf.PrefixStyle.Fixed32);
                    if (startTransaction == null || !startTransaction.Accepted)
                    {
                        Printer.PrintError("#b#Server rejected connection.##");
                        if (startTransaction != null && hs.VersionrProtocol != startTransaction.ServerHandshake.VersionrProtocol)
                            Printer.PrintError("## Protocol mismatch - local: {0}, remote: {1}", hs.VersionrProtocol, startTransaction.ServerHandshake.VersionrProtocol);
                        else
                        {
                            if (startTransaction == null)
                                Printer.PrintError("## Connection terminated unexpectedly.");
                            else
                                Printer.PrintError("## Rejected request.");
                            return false;
                        }
                        Printer.PrintError("#b#Attempting to retry with a lower protocol.##");
                        goto Retry;
                    }
                    Printer.PrintDiagnostics("Server domain: {0}", startTransaction.Domain);
                    if (Workspace != null && !string.IsNullOrEmpty(startTransaction.Domain) && startTransaction.Domain != Workspace.Domain.ToString())
                    {
                        Printer.PrintError("Server domain doesn't match client domain. Disconnecting.");
                        return false;
                    }

                    RemoteDomain = startTransaction.Domain;

                    if (SharedNetwork.SupportsAuthentication(startTransaction.ServerHandshake.CheckProtocol().Value))
                    {
                        var command = ProtoBuf.Serializer.DeserializeWithLengthPrefix<NetCommand>(Connection.GetStream(), ProtoBuf.PrefixStyle.Fixed32);
                        if (command.Type == NetCommandType.Authenticate)
                        {
                            bool runauth = true;
                            var challenge = ProtoBuf.Serializer.DeserializeWithLengthPrefix<AuthenticationChallenge>(Connection.GetStream(), ProtoBuf.PrefixStyle.Fixed32);
                            if ((!requirewrite && (command.Identifier & 1) != 0) ||
                                (requirewrite && (command.Identifier & 2) != 0)) // server supports unauthenticated access
                            {
                                AuthenticationResponse response = new AuthenticationResponse()
                                {
                                    IdentifierToken = string.Empty,
                                    Mode = AuthenticationMode.Guest
                                };
                                ProtoBuf.Serializer.SerializeWithLengthPrefix(Connection.GetStream(), response, ProtoBuf.PrefixStyle.Fixed32);
                                command = ProtoBuf.Serializer.DeserializeWithLengthPrefix<NetCommand>(Connection.GetStream(), ProtoBuf.PrefixStyle.Fixed32);
                                if (command.Type == NetCommandType.Acknowledge)
                                    runauth = false;
                            }
                            if (runauth)
                            {
                                bool q = Printer.Quiet;
                                Printer.Quiet = false;
                                Printer.PrintMessage("Server at #b#{0}## requires authentication.", VersionrURL);
                                while (true)
                                {
                                    if (challenge.AvailableModes.Contains(AuthenticationMode.Simple))
                                    {
                                        System.Console.CursorVisible = true;
                                        Printer.PrintMessageSingleLine("#b#Username:## ");
                                        string user = System.Console.ReadLine();
                                        Printer.PrintMessageSingleLine("#b#Password:## ");
                                        string pass = GetPassword();
                                        System.Console.CursorVisible = false;

                                        user = user.Trim(new char[] { '\r', '\n', ' ' });

                                        AuthenticationResponse response = new AuthenticationResponse()
                                        {
                                            IdentifierToken = user,
                                            Mode = AuthenticationMode.Simple,
                                            Payload = System.Text.ASCIIEncoding.ASCII.GetBytes(BCrypt.Net.BCrypt.HashPassword(pass, challenge.Salt))
                                        };
                                        Printer.PrintMessage("\n");
                                        ProtoBuf.Serializer.SerializeWithLengthPrefix(Connection.GetStream(), response, ProtoBuf.PrefixStyle.Fixed32);
                                        command = ProtoBuf.Serializer.DeserializeWithLengthPrefix<NetCommand>(Connection.GetStream(), ProtoBuf.PrefixStyle.Fixed32);
                                        if (command.Type == NetCommandType.AuthRetry)
                                            Printer.PrintError("#e#Authentication failed.## Retry.");
                                        if (command.Type == NetCommandType.AuthFail)
                                        {
                                            Printer.PrintError("#e#Authentication failed.##");
                                            return false;
                                        }
                                        if (command.Type == NetCommandType.Acknowledge)
                                            break;
                                    }
                                    else
                                    {
                                        Printer.PrintError("Unsupported authentication requirements!");
                                        return false;
                                    }
                                }
                                Printer.Quiet = q;
                            }
                        }
                    }
                    if (startTransaction.Encrypted)
                    {
                        var key = startTransaction.RSAKey;
                        Printer.PrintDiagnostics("Server RSA Key: {0}", key.Fingerprint());

                        var publicKey = new System.Security.Cryptography.RSACryptoServiceProvider();
                        publicKey.ImportParameters(key);

                        Printer.PrintDiagnostics("Generating secret key for data channel...");
                        System.Security.Cryptography.RSAOAEPKeyExchangeFormatter exch = new System.Security.Cryptography.RSAOAEPKeyExchangeFormatter(publicKey);

                        System.Security.Cryptography.AesManaged aesProvider = new System.Security.Cryptography.AesManaged();
                        aesProvider.KeySize = 256;
                        aesProvider.GenerateIV();
                        aesProvider.GenerateKey();

                        AESProvider = aesProvider;
                        AESKey = aesProvider.Key;
                        AESIV = aesProvider.IV;

                        Printer.PrintDiagnostics("Key: {0}", System.Convert.ToBase64String(aesProvider.Key));
                        var keyExchangeObject = new Network.StartClientTransaction() { Key = exch.CreateKeyExchange(aesProvider.Key), IV = exch.CreateKeyExchange(aesProvider.IV) };

                        ProtoBuf.Serializer.SerializeWithLengthPrefix<StartClientTransaction>(Connection.GetStream(), keyExchangeObject, ProtoBuf.PrefixStyle.Fixed32);
                        Connection.GetStream().Flush();
                        Connected = true;
                        SharedNetwork.SharedNetworkInfo sharedInfo = new SharedNetwork.SharedNetworkInfo()
                        {
                            DecryptorFunction = () => { return Decryptor; },
                            EncryptorFunction = () => { return Encryptor; },
                            Stream = Connection.GetStream(),
                            Workspace = Workspace,
                            Client = true,
                            CommunicationProtocol = protocols.Current
                        };

                        SharedInfo = sharedInfo;
                    }
                    else
                    {
                        Printer.PrintDiagnostics("Using cleartext communication");
                        var keyExchangeObject = new Network.StartClientTransaction();
                        ProtoBuf.Serializer.SerializeWithLengthPrefix<StartClientTransaction>(Connection.GetStream(), keyExchangeObject, ProtoBuf.PrefixStyle.Fixed32);
                        Connection.GetStream().Flush();
                        Connected = true;
                        SharedNetwork.SharedNetworkInfo sharedInfo = new SharedNetwork.SharedNetworkInfo()
                        {
                            DecryptorFunction = null,
                            EncryptorFunction = null,
                            Stream = Connection.GetStream(),
                            Workspace = Workspace,
                            Client = true,
                            CommunicationProtocol = protocols.Current
                        };
                        SharedInfo = sharedInfo;
                    }
                    return true;
                }
                catch (Exception e)
                {
                    Printer.PrintError("Error encountered: {0}", e);
                    return false;
                }
            }
            else
                return false;
        }
Beispiel #23
0
 public async Task ConnectAsync(System.Net.IPAddress ipAddr, int port, CancellationToken ct = default(CancellationToken), int timeout = 0)
 {
     await _TcpClient.ConnectAsync(ipAddr, port).WithCancellation(ct).WithTimeout(timeout);
 }
 public Task ConnectAsync(IPAddress address, int port)
 {
     return(_tcpClient.ConnectAsync(address, port));
 }
Beispiel #25
0
 public Task ConnectAsync(IPAddress ip, int port)
 {
     return(_client.ConnectAsync(ip, port));
 }
Beispiel #26
0
 public TcpClient()
 {
     client.ConnectAsync(IPAddress.Parse(Program.ServerIP), 17000).Wait();
 }
Beispiel #27
0
        public async void StartAsync()
        {
            System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(this.ipString);

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

            objSck = new System.Net.Sockets.TcpClient();
            // 小さいバッファを貯めない(遅延させない)
            objSck.NoDelay = true;
            try
            {
                await objSck.ConnectAsync(ipAdd, port);
            }
            catch (Exception)
            {
                //return false;
                return;
            }

            //NetworkStreamを取得
            ns = objSck.GetStream();

            ConnectResult = true;
            //return ConnectResult;
        }
 private async Task<bool> PingHost(IPEndPoint target, Guid remote_session_id, CancellationToken cancel_token)
 {
   Logger.Debug("Ping requested. Try to ping: {0}({1})", target, remote_session_id);
   bool result = false;
   try {
     var client = new System.Net.Sockets.TcpClient();
     client.ReceiveTimeout = 2000;
     client.SendTimeout    = 2000;
     await client.ConnectAsync(target.Address, target.Port);
     var stream = client.GetStream();
     await stream.WriteAsync(new Atom(Atom.PCP_CONNECT, 1), cancel_token);
     var helo = new AtomCollection();
     helo.SetHeloSessionID(PeerCast.SessionID);
     await stream.WriteAsync(new Atom(Atom.PCP_HELO, helo), cancel_token);
     var res = await stream.ReadAtomAsync(cancel_token);
     if (res.Name==Atom.PCP_OLEH) {
       var session_id = res.Children.GetHeloSessionID();
       if (session_id.HasValue && session_id.Value==remote_session_id) {
         Logger.Debug("Ping succeeded");
         result = true;
       }
       else {
         Logger.Debug("Ping failed. Remote SessionID mismatched");
       }
     }
     await stream.WriteAsync(new Atom(Atom.PCP_QUIT, Atom.PCP_ERROR_QUIT), cancel_token);
     stream.Close();
     client.Close();
   }
   catch (InvalidDataException e) {
     Logger.Debug("Ping failed");
     Logger.Debug(e);
   }
   catch (System.Net.Sockets.SocketException e) {
     Logger.Debug("Ping failed");
     Logger.Debug(e);
   }
   catch (EndOfStreamException e) {
     Logger.Debug("Ping failed");
     Logger.Debug(e);
   }
   catch (System.IO.IOException io_error) {
     Logger.Debug("Ping failed");
     Logger.Debug(io_error);
     if (!(io_error.InnerException is System.Net.Sockets.SocketException)) {
       throw;
     }
   }
   return result;
 }