当前位置: 首页>>代码示例>>C#>>正文


C# TcpClient.ConnectAsync方法代码示例

本文整理汇总了C#中System.Net.Sockets.TcpClient.ConnectAsync方法的典型用法代码示例。如果您正苦于以下问题:C# TcpClient.ConnectAsync方法的具体用法?C# TcpClient.ConnectAsync怎么用?C# TcpClient.ConnectAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Sockets.TcpClient的用法示例。


在下文中一共展示了TcpClient.ConnectAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        public static void Main(string[] args)
        {
            Console.WriteLine("Starting...");
            X509Certificate2 serverCertificate = new X509Certificate2("certificate.pfx"); // Any valid certificate with private key will work fine.
            TcpListener listener = new TcpListener(IPAddress.Any, 4567);
            TcpClient client = new TcpClient();
            listener.Start();

            Task clientConnectTask = client.ConnectAsync(IPAddress.Loopback, 4567);
            Task<TcpClient> listenerAcceptTask = listener.AcceptTcpClientAsync();
            Task.WaitAll(clientConnectTask, listenerAcceptTask);

            TcpClient server = listenerAcceptTask.Result;
            SslStream clientStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null, EncryptionPolicy.RequireEncryption);
            SslStream serverStream = new SslStream(server.GetStream(), false, null, null, EncryptionPolicy.RequireEncryption);

            Task clientAuthenticationTask = clientStream.AuthenticateAsClientAsync(serverCertificate.GetNameInfo(X509NameType.SimpleName, false), null, SslProtocols.Tls12, false);
            Task serverAuthenticationTask = serverStream.AuthenticateAsServerAsync(serverCertificate, false, SslProtocols.Tls12, false);
            Task.WaitAll(clientAuthenticationTask, serverAuthenticationTask);
            
            byte[] readBuffer = new byte[256];
            Task<int> readTask = clientStream.ReadAsync(readBuffer, 0, readBuffer.Length); // Create a pending ReadAsync, which will wait for data that will never come (for testing purposes).
            byte[] writeBuffer = new byte[256];
            Task writeTask = clientStream.WriteAsync(writeBuffer, 0, writeBuffer.Length); // The main thread actually blocks here (not asychronously waits) on .NET Core making this call.
            bool result = Task.WaitAll(new Task[1] { writeTask }, 5000); // This code won't even be reached on .NET Core. Works fine on .NET Framework.

            if (result)
            {
                Console.WriteLine("WriteAsync completed successfully while ReadAsync was pending... nothing locked up.");
            }
            else
            {
                Console.WriteLine("WriteAsync failed to complete after 5 seconds.");
            }
        }
开发者ID:xanather,项目名称:SslStreamTest,代码行数:35,代码来源:Program.cs

示例2: ConnectToServerAsync

 public static async Task<Socket> ConnectToServerAsync(IPEndPoint endpoint, IEnumerable<AddressFamily> addressFamilies)
 {
     ValidateEndpoint(endpoint, addressFamilies);
     var tcpClient = new TcpClient();
     await tcpClient.ConnectAsync(endpoint.Address, endpoint.Port);
     return tcpClient.Client;
 }
开发者ID:tablesmit,项目名称:SocketToMe,代码行数:7,代码来源:Tcp.cs

示例3: ServerNoEncryption_ClientNoEncryption_ConnectWithNoEncryption

        public async Task ServerNoEncryption_ClientNoEncryption_ConnectWithNoEncryption()
        {
            using (var serverNoEncryption = new DummyTcpServer(
                new IPEndPoint(IPAddress.Loopback, 0), EncryptionPolicy.NoEncryption))
            using (var client = new TcpClient())
            {
                await client.ConnectAsync(serverNoEncryption.RemoteEndPoint.Address, serverNoEncryption.RemoteEndPoint.Port);

                using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null, EncryptionPolicy.NoEncryption))
                {
                    if (SupportsNullEncryption)
                    {
                        await sslStream.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false);
                        _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength",
                            serverNoEncryption.RemoteEndPoint, sslStream.CipherAlgorithm, sslStream.CipherStrength);

                        CipherAlgorithmType expected = CipherAlgorithmType.Null;
                        Assert.Equal(expected, sslStream.CipherAlgorithm);
                        Assert.Equal(0, sslStream.CipherStrength);
                    }
                    else
                    {
                        var ae = await Assert.ThrowsAsync<AuthenticationException>(() => sslStream.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false));
                        Assert.IsType<PlatformNotSupportedException>(ae.InnerException);
                    }
                }
            }
        }
开发者ID:Corillian,项目名称:corefx,代码行数:28,代码来源:ServerNoEncryptionTest.cs

示例4: StartClientToServerComms

        private async Task StartClientToServerComms()
        {
            string host = "10.1.1.84";
            int port = 58846;
            Console.WriteLine("[Relay] Connecting to {0}:{1}", host, port);

            using (var nextTcpClient = new TcpClient())
            {
                await nextTcpClient.ConnectAsync(host, port);
                Console.WriteLine("[Relay] Connected to server");
                byte[] clientBuffer = new byte[4096];
                using (var clientToServerNetworkStream = new SslStream(nextTcpClient.GetStream(), true,
                    (sender, certificate, chain, errors) => { return true; }))
                {

                    clientToServerNetworkStream.AuthenticateAsClient(host);
                    while (true)
                    {
                        var clientBytes = await clientToServerNetworkStream.ReadAsync(clientBuffer, 0, clientBuffer.Length);

                        if (clientBytes > 0)
                        {
                            Console.WriteLine("Client sent {0}", DelugeRPC.DelugeProtocol.DecompressAndDecode(clientBuffer).Dump());
                            await clientToServerNetworkStream.WriteAsync(clientBuffer, 0, clientBuffer.Length);
                        }
                    }
                }
            }
        }
开发者ID:voltagex,项目名称:junkcode,代码行数:29,代码来源:Program.cs

示例5: Run

        private static async Task<int> Run(int port) {
            using (var client = new TcpClient()) {
                await client.ConnectAsync(IPAddress.Loopback, port);

                var utf8 = new UTF8Encoding(false);
                using (var reader = new StreamReader(client.GetStream(), utf8, false, 4096, true))
                using (var writer = new StreamWriter(client.GetStream(), utf8, 4096, true)) {
                    var filename = await reader.ReadLineAsync();
                    var args = (await reader.ReadLineAsync()).Split('|')
                        .Select(s => utf8.GetString(Convert.FromBase64String(s)))
                        .ToList();
                    var workingDir = await reader.ReadLineAsync();
                    var env = (await reader.ReadLineAsync()).Split('|')
                        .Select(s => s.Split(new[] { '=' }, 2))
                        .Select(s => new KeyValuePair<string, string>(s[0], utf8.GetString(Convert.FromBase64String(s[1]))))
                        .ToList();
                    var outputEncoding = await reader.ReadLineAsync();
                    var errorEncoding = await reader.ReadLineAsync();

                    return await ProcessOutput.Run(
                        filename,
                        args,
                        workingDir,
                        env,
                        false,
                        new StreamRedirector(writer, outputPrefix: "OUT:", errorPrefix: "ERR:"),
                        quoteArgs: false,
                        elevate: false,
                        outputEncoding: string.IsNullOrEmpty(outputEncoding) ? null : Encoding.GetEncoding(outputEncoding),
                        errorEncoding: string.IsNullOrEmpty(errorEncoding) ? null : Encoding.GetEncoding(errorEncoding)
                    );
                }
            }
        }
开发者ID:zooba,项目名称:PTVS,代码行数:34,代码来源:Program.cs

示例6: ConnectAsync

	    public async Task<TcpClient> ConnectAsync(string hostname, int port)
	    {
	        TcpClient client = new TcpClient();
	        await client.ConnectAsync(hostname, port);
	        DoHandshake(client, hostname, port);
	        return client;
	    } 
开发者ID:pendo324,项目名称:Cobalt,代码行数:7,代码来源:SocksTcpClient.cs

示例7: timer1_Tick

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                TcpClient tcpclnt = new TcpClient();

                label4.Text = "Attempting to connect to RPi...";

                if (tcpclnt.ConnectAsync("192.168.55.3", 5069).Wait(1000))
                {
                    label4.Text = "Couldn't connect to RPi";
                }
                else
                {
                    label4.Text = "Connected to RPi";

                    this.Hide();

                    Form MainForm = new MainForm();
                    MainForm.Show();

                    timer1.Dispose();
                }
            }
            else
            {
                label4.Text = "Waiting for network...";
            }
        }
开发者ID:KiloSierraCharlie,项目名称:G-ABFE,代码行数:29,代码来源:Load.cs

示例8: Main

        public static void Main(string[] args)
        {
            if(args.Length != 1)
            {
                Console.WriteLine("need ipadress ");
                return;
            }
            IPAddress ipAddress = IPAddress.Parse(args[0]);
            int port = 7681;

            TcpClient client = new TcpClient();
            client.ConnectAsync(ipAddress, port).Wait();
            Console.WriteLine("connected");
            using (NegotiateStream stream = new NegotiateStream(client.GetStream()))
            {
                Console.WriteLine("authenticating");
                stream.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, null, "HOST/skapilac10.fareast.corp.microsoft.com").Wait();
                Console.WriteLine("authenticated");
                var sendBuffer = Encoding.UTF8.GetBytes("Request from client");
                stream.Write(sendBuffer, 0, sendBuffer.Length);
                var recvBuffer = new byte[1024];
                var byteCount = stream.Read(recvBuffer, 0, recvBuffer.Length);
                Console.WriteLine("Recieved: {0}", Encoding.UTF8.GetString(recvBuffer, 0, byteCount));
            }
        }
开发者ID:kapilash,项目名称:dc,代码行数:25,代码来源:Program.cs

示例9: Initialize

        public override bool Initialize()
        {
            Logger.Log($"Connecting to Twitch IRC -> {Account.Username}");

            _Client = new TcpClient();
            _Client.ConnectAsync("irc.twitch.tv", 6667).Wait();

            _Writer = new StreamWriter(_Client.GetStream());
            _Reader = new StreamReader(_Client.GetStream());

            Logger.Log("Sending login credentials");

            _SendStringRaw($"PASS {Account.OAuth}");
            _SendStringRaw($"NICK {Account.Username}");

            var response = IRCMessage.Parse(_Reader.ReadLine());
            if (response.Type != "001")
            {
                Logger.Log("Server did not return expected login message");
                return false;
            }

            // runners
            new Thread(_SendRunner).Start();
            new Thread(_ReceiveRunner).Start();

            Logger.Log("Connecting to channels");
            foreach (var c in Channels)
                _SendString($"JOIN #{c}", MessagePriority.Medium);

            return true;
        }
开发者ID:Zogzer,项目名称:Applebot,代码行数:32,代码来源:TwitchConnection.cs

示例10: ConnectAsync

		/// <summary>
		/// Connects the client to a remote host using the specified 
		/// IP address and port number as an asynchronous operation.
		/// </summary>
		/// <param name="host">host.</param>
		/// <param name="port">port.</param>
		/// <param name="certificate">certificate.</param>
		/// <exception cref="ConnectionInterruptedException"></exception>
		public async Task ConnectAsync(string host, int port, X509Certificate2 certificate)
		{
			try
			{
				// connect via tcp
				tcpClient = new TcpClient();
				await tcpClient.ConnectAsync(host, port);

				await Task.Run(() =>
				{
					// create ssl stream
					sslStream = new SslStream(tcpClient.GetStream(), true,
						Ssl.ServerValidationCallback,
						Ssl.ClientCertificateSelectionCallback,
						EncryptionPolicy.RequireEncryption);

					// handshake
					Ssl.ClientSideHandshake(certificate, sslStream, host);
				});
			}
			catch (CertificateException e)
			{
				throw new ConnectionInterruptedException("Connection failed. Reason: " + e.Message);
			}
			catch
			{
				throw new ConnectionInterruptedException("Connection failed.");
			}
		}
开发者ID:pr3sto,项目名称:CryptoMessenger,代码行数:37,代码来源:MessageProtocol.cs

示例11: Connect

        public async Task<bool> Connect(string hostname, int port)
        {
            if(ServerConnectionStarting != null)
                ServerConnectionStarting(this, new ServerConnectionEventArgs{Message = "Connecting to " + hostname + ":" + port.ToString() + "...", Status = ServerConnectionStatus.Connecting, Timestamp = DateTime.Now});

            try
            {
                TcpClient = new TcpClient();
                TcpClient.NoDelay = true;
                await TcpClient.ConnectAsync(hostname, port);
            }
            catch
            {
                if(ServerConnectionFailed != null)
                    ServerConnectionFailed(this, new ServerConnectionEventArgs{Message = "Failed to connect!  Make sure the server is running and that your hostname and port are correct.", Status = ServerConnectionStatus.Disconnected, Timestamp = DateTime.Now});
            }
            if(IsConnected)
            {
                TcpClientStream = TcpClient.GetStream();

                if(ServerConnectionSucceeded != null)
                    ServerConnectionSucceeded(this, new ServerConnectionEventArgs{Message = "Successfully connected.", Status = ServerConnectionStatus.Connected, Timestamp = DateTime.Now});

                Keepalive.Reset();
                return true;
            }
            else return false;
        }
开发者ID:Lordicon,项目名称:ArkServerManager,代码行数:28,代码来源:Client.cs

示例12: Download

        public void Download()
        {
            using (TcpClient tcpClient = new TcpClient())
            {
                if (!tcpClient.ConnectAsync(IpAdress, 80).Wait(TIMEOUT))
                {
                    Console.WriteLine("La connection vers " + Uri + " a timeout");
                    return;
                }
                stream = tcpClient.GetStream();

                var byteRequest = Encoding.ASCII.GetBytes(string.Format(GetRequest, Uri.LocalPath, Uri.Host));
                stream.Write(byteRequest, 0, byteRequest.Length);
                bufferSize = tcpClient.ReceiveBufferSize;

                List<byte> srcByte = new List<byte>();
                while (!stream.DataAvailable) ;
                while (stream.DataAvailable)
                {
                    byte[] data = new byte[bufferSize];
                    int read = stream.Read(data, 0, bufferSize);
                    srcByte.AddRange(data.Take(read));
                }

                ParseRequest(srcByte.ToArray());
            }
        }
开发者ID:Dref360,项目名称:IFT585-tp3,代码行数:27,代码来源:HTTPDownloadableContent.cs

示例13: SendServiceMessage

        private async Task SendServiceMessage(Message packet)
        {
            var command = packet.Json;
            try
            {
                using (var tcpClient = new TcpClient())
                {
                    await tcpClient.ConnectAsync(IPAddress.Loopback, 22005);
                    using (var stream = tcpClient.GetStream())
                    using (var sw = new StreamWriter(stream, Encoding.UTF8))
                    {

                        if (tcpClient.Connected)
                        {
                            await sw.WriteLineAsync(command);
                            await sw.FlushAsync();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
开发者ID:Ulterius,项目名称:server,代码行数:25,代码来源:MessageQueueManager.cs

示例14: Send

        protected override async Task Send(SyslogMessage syslogMessage)
        {
            var client = new TcpClient();
            client.ConnectAsync(Hostname, LogglyConfig.Instance.Transport.EndpointPort).Wait();

            try
            {
                byte[] messageBytes = syslogMessage.GetBytes();
                var networkStream = await GetNetworkStream(client).ConfigureAwait(false);
                await networkStream.WriteAsync(messageBytes, 0, messageBytes.Length).ConfigureAwait(false);
                await networkStream.FlushAsync().ConfigureAwait(false);
            }
            catch (AuthenticationException e)
            {
                LogglyException.Throw(e, e.Message);
            }
            finally
            {
#if NET_STANDARD
                client.Dispose();
#else
                client.Close();
#endif
            }

        }
开发者ID:neutmute,项目名称:loggly-csharp,代码行数:26,代码来源:SyslogTcpTransport.cs

示例15: PostEmailAsync

 public override Task PostEmailAsync(string name, string[] to, string[] cc, string[] bcc, string subject, string message, params Attachment[] Attachments)
 {
     if (!ssl)
         return Task.Factory.StartNew(async () =>
         {
             using (var client = new TcpClient())
             {
                 await client.ConnectAsync(server, port);
                 using (var stream = client.GetStream())
                 using (var reader = new StreamReader(stream))
                 using (var writer = new StreamWriter(stream) { AutoFlush = true, NewLine = "\r\n" })
                 {
                     TcpWrite(writer, reader, name, to, cc, bcc, subject, message, Attachments);
                 }
             }
         });
     else
         return Task.Factory.StartNew(async () =>
         {
             using (var client = new TcpClient())
             {
                 await client.ConnectAsync(server, port);
                 using (var stream = new SslStream(client.GetStream(), false))
                 {
                     await stream.AuthenticateAsClientAsync(server);
                     using (var reader = new StreamReader(stream))
                     using (var writer = new StreamWriter(stream) { AutoFlush = true, NewLine = "\r\n" })
                     {
                         TcpWrite(writer, reader, name, to, cc, bcc, subject, message, Attachments);
                     }
                 }
             }
         });
 }
开发者ID:yonglehou,项目名称:dotNETCore-Extensions,代码行数:34,代码来源:SmtpEmailSender.cs


注:本文中的System.Net.Sockets.TcpClient.ConnectAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。