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


C# TcpClient.ConnectAsync方法代码示例

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


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

示例1: Connect_DnsEndPoint_Success

        public async Task Connect_DnsEndPoint_Success(int mode)
        {
            using (TcpClient client = new TcpClient())
            {
                Assert.False(client.Connected);

                string host = HttpTestServers.Host;
                const int port = 80;

                if (mode == 0)
                {
                    await client.ConnectAsync(host, port);
                }
                else
                {
                    IPAddress[] addresses = await Dns.GetHostAddressesAsync(host);
                    await (mode == 1 ?
                        client.ConnectAsync(addresses[0], port) :
                        client.ConnectAsync(addresses, port));
                }

                Assert.True(client.Connected);
                Assert.NotNull(client.Client);
                Assert.Same(client.Client, client.Client);

                using (NetworkStream s = client.GetStream())
                {
                    byte[] getRequest = Encoding.ASCII.GetBytes("GET / HTTP/1.1\r\n\r\n");
                    await s.WriteAsync(getRequest, 0, getRequest.Length);
                    Assert.NotEqual(-1, s.ReadByte()); // just verify we successfully get any data back
                }
            }
        }
开发者ID:rahulkotecha,项目名称:corefx,代码行数:33,代码来源:TcpClientTest.cs

示例2: ConnectAsync_DnsEndPoint_Success

        public async Task ConnectAsync_DnsEndPoint_Success(int mode)
        {
            using (TcpClient client = new TcpClient())
            {
                Assert.False(client.Connected);

                string host = System.Net.Test.Common.Configuration.Sockets.SocketServer.IdnHost;
                int port = System.Net.Test.Common.Configuration.Sockets.SocketServer.Port;

                IPAddress[] addresses;
                switch (mode)
                {
                    case 0:
                        await client.ConnectAsync(host, port);
                        break;
                    case 1:
                        addresses = await Dns.GetHostAddressesAsync(host);
                        await client.ConnectAsync(addresses[0], port);
                        break;
                    case 2:
                        addresses = await Dns.GetHostAddressesAsync(host);
                        await client.ConnectAsync(addresses, port);
                        break;

                    case 3:
                        await Task.Factory.FromAsync(client.BeginConnect, client.EndConnect, host, port, null);
                        break;
                    case 4:
                        addresses = await Dns.GetHostAddressesAsync(host);
                        await Task.Factory.FromAsync(client.BeginConnect, client.EndConnect, addresses[0], port, null);
                        break;
                    case 5:
                        addresses = await Dns.GetHostAddressesAsync(host);
                        await Task.Factory.FromAsync(client.BeginConnect, client.EndConnect, addresses, port, null);
                        break;
                }

                Assert.True(client.Connected);
                Assert.NotNull(client.Client);
                Assert.Same(client.Client, client.Client);

                using (NetworkStream s = client.GetStream())
                {
                    byte[] getRequest = Encoding.ASCII.GetBytes("GET / HTTP/1.1\r\n\r\n");
                    await s.WriteAsync(getRequest, 0, getRequest.Length);
                    Assert.NotEqual(-1, s.ReadByte()); // just verify we successfully get any data back
                }
            }
        }
开发者ID:dotnet,项目名称:corefx,代码行数:49,代码来源:TcpClientTest.cs

示例3: ConnectWithV4AndV6_Success

        public void ConnectWithV4AndV6_Success()
        {
            int port;
            TcpListener listener = SocketTestExtensions.CreateAndStartTcpListenerOnAnonymousPort(out port);
            IAsyncResult asyncResult = listener.BeginAcceptTcpClient(null, null);

            TcpClient v6Client = new TcpClient(AddressFamily.InterNetworkV6);
            v6Client.ConnectAsync(IPAddress.IPv6Loopback, port).GetAwaiter().GetResult();

            TcpClient acceptedV6Client = listener.EndAcceptTcpClient(asyncResult);
            Assert.Equal(AddressFamily.InterNetworkV6, acceptedV6Client.Client.RemoteEndPoint.AddressFamily);
            Assert.Equal(AddressFamily.InterNetworkV6, v6Client.Client.RemoteEndPoint.AddressFamily);

            asyncResult = listener.BeginAcceptTcpClient(null, null);

            TcpClient v4Client = new TcpClient(AddressFamily.InterNetwork);
            v4Client.ConnectAsync(IPAddress.Loopback, port).GetAwaiter().GetResult();

            TcpClient acceptedV4Client = listener.EndAcceptTcpClient(asyncResult);
            Assert.Equal(AddressFamily.InterNetworkV6, acceptedV4Client.Client.RemoteEndPoint.AddressFamily);
            Assert.Equal(AddressFamily.InterNetwork, v4Client.Client.RemoteEndPoint.AddressFamily);

            v6Client.Dispose();
            acceptedV6Client.Dispose();

            v4Client.Dispose();
            acceptedV4Client.Dispose();

            listener.Stop();
        }
开发者ID:Corillian,项目名称:corefx,代码行数:30,代码来源:AgnosticListenerTest.cs

示例4: RunWithConnectedNetworkStreamsAsync

        /// <summary>
        /// Creates a pair of connected NetworkStreams and invokes the provided <paramref name="func"/>
        /// with them as arguments.
        /// </summary>
        private static async Task RunWithConnectedNetworkStreamsAsync(Func<NetworkStream, NetworkStream, Task> func)
        {
            var listener = new TcpListener(IPAddress.Loopback, 0);
            try
            {
                listener.Start(1);
                var clientEndpoint = (IPEndPoint)listener.LocalEndpoint;

                using (var client = new TcpClient(clientEndpoint.AddressFamily))
                {
                    Task<TcpClient> remoteTask = listener.AcceptTcpClientAsync();
                    Task clientConnectTask = client.ConnectAsync(clientEndpoint.Address, clientEndpoint.Port);

                    await Task.WhenAll(remoteTask, clientConnectTask);

                    using (TcpClient remote = remoteTask.Result)
                    using (NetworkStream serverStream = remote.GetStream())
                    using (NetworkStream clientStream = client.GetStream())
                    {
                        await func(serverStream, clientStream);
                    }
                }
            }
            finally
            {
                listener.Stop();
            }
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:32,代码来源:NetworkStreamTest.cs

示例5: StartClient

		private static async Task StartClient(IPAddress serverIpAddress, int port, byte[] message)
		{
			using (var client = new TcpClient())
			{
				try
				{
					await client.ConnectAsync(serverIpAddress, port);
					Logger("Connected to server");
					using (var networkStream = client.GetStream())
					{
						if (networkStream.CanWrite)
						{
							//var writeBuffer = Encoding.ASCII.GetBytes(message);
							await networkStream.WriteAsync(message, 0, message.Length);
							//Logger.Info("Sent : " + Encoding.ASCII.GetString(message));
							Logger("Sent : " + BitConverter.ToString(message));
						}
						else
						{
							Logger("Cannot write from this NetworkStream.");
						}

						var accumBuffer = new byte[] { };
						// Check to see if this NetworkStream is readable. 
						if (networkStream.CanRead)
						{
							var readBuffer = new byte[1500];

							// Incoming message may be larger than the buffer size. 
							do
							{
								var numberOfBytesRead = await networkStream.ReadAsync(readBuffer, 0, readBuffer.Length);
								accumBuffer = Combine(accumBuffer, readBuffer, numberOfBytesRead);
							}
							while (networkStream.DataAvailable);

							//Logger.Info("Received : " + Encoding.ASCII.GetString(accumBuffer));
							Logger("Received : " + BitConverter.ToString(accumBuffer));
						}
						else
						{
							Logger("Cannot read from this NetworkStream.");
						}
					}
				}
				catch (Exception e)
				{
					Logger(e);
				}
			}
		}
开发者ID:publicENEMY,项目名称:FuntionalPrototype,代码行数:51,代码来源:MainPage.xaml.cs

示例6: ConnectWithV6_Success

        public void ConnectWithV6_Success()
        {
            int port;
            TcpListener listener = SocketTestExtensions.CreateAndStartTcpListenerOnAnonymousPort(out port);
            IAsyncResult asyncResult = listener.BeginAcceptTcpClient(null, null);

            TcpClient client = new TcpClient(AddressFamily.InterNetworkV6);
            client.ConnectAsync(IPAddress.IPv6Loopback, port).GetAwaiter().GetResult();

            TcpClient acceptedClient = listener.EndAcceptTcpClient(asyncResult);
            client.Dispose();
            acceptedClient.Dispose();
            listener.Stop();
        }
开发者ID:Corillian,项目名称:corefx,代码行数:14,代码来源:AgnosticListenerTest.cs

示例7: SendRecvAsync_TcpListener_TcpClient

        public void SendRecvAsync_TcpListener_TcpClient(IPAddress listenAt)
        {
            const int BytesToSend = 123456;
            const int ListenBacklog = 1;
            const int LingerTime = 10;
            const int TestTimeout = 30000;

            var listener = new TcpListener(listenAt, 0);
            listener.Start(ListenBacklog);

            int bytesReceived = 0;
            var receivedChecksum = new Fletcher32();
            Task serverTask = Task.Run(async () =>
            {
                using (TcpClient remote = await listener.AcceptTcpClientAsync())
                using (NetworkStream stream = remote.GetStream())
                {
                    var recvBuffer = new byte[256];
                    for (;;)
                    {
                        int received = await stream.ReadAsync(recvBuffer, 0, recvBuffer.Length);
                        if (received == 0)
                        {
                            break;
                        }

                        bytesReceived += received;
                        receivedChecksum.Add(recvBuffer, 0, received);
                    }
                }
            });

            int bytesSent = 0;
            var sentChecksum = new Fletcher32();
            Task clientTask = Task.Run(async () =>
            {
                var clientEndpoint = (IPEndPoint)listener.LocalEndpoint;

                using (var client = new TcpClient(clientEndpoint.AddressFamily))
                {
                    await client.ConnectAsync(clientEndpoint.Address, clientEndpoint.Port);

                    using (NetworkStream stream = client.GetStream())
                    {
                        var random = new Random();
                        var sendBuffer = new byte[512];
                        for (int remaining = BytesToSend, sent = 0; remaining > 0; remaining -= sent)
                        {
                            random.NextBytes(sendBuffer);

                            sent = Math.Min(sendBuffer.Length, remaining);
                            await stream.WriteAsync(sendBuffer, 0, sent);

                            bytesSent += sent;
                            sentChecksum.Add(sendBuffer, 0, sent);
                        }

                        client.LingerState = new LingerOption(true, LingerTime);
                    }
                }
            });

            Assert.True(Task.WaitAll(new[] { serverTask, clientTask }, TestTimeout));

            Assert.Equal(bytesSent, bytesReceived);
            Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum);
        }
开发者ID:ChuangYang,项目名称:corefx,代码行数:67,代码来源:SendReceive.cs

示例8: Properties_PersistAfterConnect

        public async Task Properties_PersistAfterConnect()
        {
            using (TcpClient client = new TcpClient())
            {
                // Set a few properties
                client.LingerState = new LingerOption(true, 1);
                client.ReceiveTimeout = 42;
                client.SendTimeout = 84;

                await client.ConnectAsync(HttpTestServers.Host, 80);

                // Verify their values remain as were set before connecting
                Assert.True(client.LingerState.Enabled);
                Assert.Equal(1, client.LingerState.LingerTime);
                Assert.Equal(42, client.ReceiveTimeout);
                Assert.Equal(84, client.SendTimeout);

                // Note: not all properties can be tested for this on all OSes, as some
                // properties are modified by the OS, e.g. Linux will double whatever
                // buffer size you set and return that double value.  OSes may also enforce
                // minimums and maximums, silently capping to those amounts.
            }
        }
开发者ID:rahulkotecha,项目名称:corefx,代码行数:23,代码来源:TcpClientTest.cs

示例9: Dispose_CancelsConnectAsync

        public async Task Dispose_CancelsConnectAsync(bool connectByName)
        {
            using (var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                // Set up a server socket to which to connect
                server.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                server.Listen(1);
                var endpoint = (IPEndPoint)server.LocalEndPoint;

                // Connect asynchronously...
                var client = new TcpClient();
                Task connectTask = connectByName ?
                    client.ConnectAsync("localhost", endpoint.Port) :
                    client.ConnectAsync(endpoint.Address, endpoint.Port);

                // ...and hopefully before it's completed connecting, dispose.
                var sw = Stopwatch.StartNew();
                client.Dispose();

                // There is a race condition here.  If the connection succeeds before the
                // disposal, then the task will complete successfully.  Otherwise, it should
                // fail with an ObjectDisposedException.
                try
                {
                    await connectTask;
                }
                catch (ObjectDisposedException) { }
                sw.Stop();

                Assert.Null(client.Client); // should be nulled out after Dispose
            }
        }
开发者ID:SamuelEnglard,项目名称:corefx,代码行数:32,代码来源:TcpClientTest.cs

示例10: TcpClient_ConnectAsync_ArrayOfAddresses_NotSupportedAfterClientAccess

 public void TcpClient_ConnectAsync_ArrayOfAddresses_NotSupportedAfterClientAccess()
 {
     using (TcpClient client = new TcpClient())
     {
         var tmp = client.Client;
         Assert.Throws<PlatformNotSupportedException>(() => { client.ConnectAsync(new[] { IPAddress.Loopback }, 12345); });
     }
 }
开发者ID:shmao,项目名称:corefx,代码行数:8,代码来源:ArgumentValidationTests.cs

示例11: TcpClient_ConnectAsync_StringHost_NotSupportedAfterClientAccess

 public void TcpClient_ConnectAsync_StringHost_NotSupportedAfterClientAccess()
 {
     using (TcpClient client = new TcpClient())
     {
         var tmp = client.Client;
         Assert.Throws<PlatformNotSupportedException>(() => { client.ConnectAsync("localhost", 12345); });
     }
 }
开发者ID:shmao,项目名称:corefx,代码行数:8,代码来源:ArgumentValidationTests.cs


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