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


C# TcpListener.AcceptTcpClientAsync方法代码示例

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


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

示例1: StartListener

 private void StartListener(IPEndPoint endPoint)
 {
     _listener = new TcpListener(endPoint);
     _listener.Start(5);
     _log.WriteLine("Server {0} listening", endPoint.Address.ToString());
     _listener.AcceptTcpClientAsync().ContinueWith(t => OnAccept(t), TaskScheduler.Default);
 }
开发者ID:SGuyGe,项目名称:corefx,代码行数:7,代码来源:DummyTcpServer.cs

示例2: 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

示例3: HandleClients

        public static IDisposable HandleClients(TcpListener listener, Func<TcpClient, string, Task> handleClientAccessPolicy, string policyResponse)
        {
            listener.Start();

            var disposableHandler = ThreadPoolScheduler.Instance.ScheduleAsync(async (scheduler, ct) =>
            {
                var disposable = new BooleanDisposable();

                while (!disposable.IsDisposed)
                {
                    var client = await listener.AcceptTcpClientAsync();
                    await handleClientAccessPolicy(client, policyResponse);
                    await scheduler.Yield();
                }

                return disposable;
            });

            var compositeDisposable = new CompositeDisposable();

            compositeDisposable.Add(Disposable.Create(() => listener.Stop()));
            compositeDisposable.Add(disposableHandler);

            return compositeDisposable;
        }
开发者ID:vgrigoriu,项目名称:Redis.SilverlightClient,代码行数:25,代码来源:PolicyHandler.cs

示例4: TestTcpLisener

        public static void TestTcpLisener()
        {
            var tcpListener = new TcpListener(IPAddress.Any, 3456);
            tcpListener.Start();
            tcpListener.AcceptTcpClientAsync();

            var tcpClient = new TcpClient();
            tcpClient.Connect(IPAddress.Parse("127.0.0.1"), 3456);

            var clnt = tcpListener.AcceptTcpClientAsync().ConfigureAwait(true).GetAwaiter().GetResult();
        }
开发者ID:johnsmith9264,项目名称:MyChat,代码行数:11,代码来源:NetworkTests.cs

示例5: RunServerAsync

 /// <summary>
 /// Method to be used on seperate thread.
 /// </summary>
 private Task RunServerAsync()
 {
     return Task.Run(async () =>
     {
         try
         {
             logger.Info("Starting tcp server on port {0}", settings.Port);
             var listener = new TcpListener(IPAddress.Any, settings.Port);
             listener.Start();
             while (runServer)
             {
                 try
                 {
                     var client = await listener.AcceptTcpClientAsync().WithCancellation(cancellationToken.Token);
                     logger.Info("Got new TCP client from {0}", client.Client.RemoteEndPoint as IPEndPoint);
                     tcpClients.AddLast(client);
                     HandleClientAsync(client);
                 }
                 catch (Exception exp)
                 {
                     logger.Error(exp, "Exception while waiting for new TCP client.");
                 }
             }
         }
         catch (Exception exp)
         {
             logger.Error(exp, "Exception starting Tcp Server.");
         }
     });
 }
开发者ID:audioview2016,项目名称:AudioView2,代码行数:33,代码来源:TCPServerListener.cs

示例6: AcceptClient

 static async Task AcceptClient (TcpListener server, TaskCompletionSource<byte[]> result)
 {
     using (var client = await server.AcceptTcpClientAsync ())
     using (var stream = client.GetStream ()) {
         result.SetResult (await DataStreamReader.ReadDataAsync (stream));
     }
 }
开发者ID:jagrem,项目名称:msg,代码行数:7,代码来源:TcpServer.cs

示例7: TestTcpTraceListener

        public async Task TestTcpTraceListener()
        {
            var listener = new TcpListener(IPAddress.Loopback, 0);
            listener.Start();
            int port = ((IPEndPoint)listener.Server.LocalEndPoint).Port;


            var traceSource = new TraceSource("UnitTestLogger");
            traceSource.Listeners.Remove("Default");
            traceSource.Switch.Level = SourceLevels.All;
            traceSource.Listeners.Add(new TcpTraceListener(
                                            IPAddress.Loopback, port, 
                                            new ExponentialBackoffTcpReconnectionPolicy()));

            var listenerClient = await listener.AcceptTcpClientAsync();

            traceSource.TraceEvent(TraceEventType.Information, 100, "Boris");

            var receiverReader = new StreamReader(listenerClient.GetStream());
            var line = await receiverReader.ReadLineAsync();

            Assert.True(line.EndsWith("UnitTestLogger Information: 100 : Boris"));

            listenerClient.Close();
            listener.Stop();
            traceSource.Close();
        }
开发者ID:JimSimpkins13,项目名称:splunk-library-dotnetlogging,代码行数:27,代码来源:TestTcp.cs

示例8: TestEventSink

        public async Task TestEventSink()
        {
            var listener = new TcpListener(IPAddress.Loopback, 0);
            listener.Start();
            int port = ((IPEndPoint)listener.Server.LocalEndPoint).Port;

            var slabListener = new ObservableEventListener();
            slabListener.Subscribe(new TcpEventSink(IPAddress.Loopback, port, 
                new ExponentialBackoffTcpReconnectionPolicy(),
                new TestEventFormatter()));
            var source = TestEventSource.GetInstance();
            slabListener.EnableEvents(source, EventLevel.LogAlways, Keywords.All);

            var listenerClient = await listener.AcceptTcpClientAsync();

            source.Message("Boris", "Meep");

            var receiverReader = new StreamReader(listenerClient.GetStream());
            var line = await receiverReader.ReadLineAsync();

            Assert.Equal(
                "EventId=1 EventName=MessageInfo Level=Error \"FormattedMessage=Meep - Boris\" \"message=Boris\" \"caller=Meep\"",
                line);

            listenerClient.Close();
            listener.Stop();
            slabListener.Dispose();
        }
开发者ID:JimSimpkins13,项目名称:splunk-library-dotnetlogging,代码行数:28,代码来源:TestTcp.cs

示例9: SendReceiveAndVerify_keeps_SendTimeout_ReceiveTimeout

        public void SendReceiveAndVerify_keeps_SendTimeout_ReceiveTimeout()
        {
            var endpoint = TestHelpers.CreateEndpointForTransport(RedFoxTransport.Tcp);
            var socketConfiguration = new SocketConfiguration
            {
                SendTimeout = TimeSpan.FromSeconds(10),
                ReceiveTimeout = TimeSpan.FromSeconds(20)
            };

            var server = new TcpListener(IPAddress.Loopback, endpoint.Port);
            server.Start();
            try
            {
                server.AcceptTcpClientAsync();

                var nodeGreetingVerifier = new NodeGreetingMessageVerifier(NodeType.Requester, NodeType.Responder);

                var socket = (TcpSocket)new SocketFactory().CreateAndConnectAsync(endpoint, NodeType.Responder, socketConfiguration);
                Assert.Throws<TimeoutException>(() => nodeGreetingVerifier.SendReceiveAndVerify(socket, TimeSpan.FromSeconds(2)));

                Assert.AreEqual(socketConfiguration.SendTimeout.ToMillisOrZero(), socket.TcpClient.SendTimeout);
                Assert.AreEqual(socketConfiguration.ReceiveTimeout.ToMillisOrZero(), socket.TcpClient.ReceiveTimeout);
            }
            finally
            {
                server.Stop();
            }
        }
开发者ID:tleviathan,项目名称:redfoxmq,代码行数:28,代码来源:NodeGreetingMessageVerifierTests.cs

示例10: Start

        public Task Start(CancellationToken cancellationToken)
        {
            Console.WriteLine($"Starting viewer connector on port {_listenerPort}.");
            var listener = new TcpListener(IPAddress.Any, _listenerPort);
            listener.Start();

            return Task.Run(async () =>
            {
                var clients = new List<Task>();
                try
                {
                    while (!cancellationToken.IsCancellationRequested)
                    {
                        var tcpClient =
                            await listener.AcceptTcpClientAsync().ContinueWith(t => t.Result, cancellationToken);
                        clients = clients.Where(task => !task.IsCompleted).ToList();
                        clients.Add(HandleSinglePlayer(tcpClient, cancellationToken));
                    }
                }
                finally
                {
                    await Task.WhenAll(clients.ToArray());
                }
            }, cancellationToken);
        }
开发者ID:ksuszka,项目名称:SnakeWars,代码行数:25,代码来源:ViewersConnector.cs

示例11: ReadFromClient

        private static string ReadFromClient()
        {
            TcpListener listener = null;
            try
            {
                listener = new TcpListener(IPAddress.Any, 6740);
                listener.Start();
                var acceptTcpClientAsync = listener.AcceptTcpClientAsync();
                acceptTcpClientAsync.Wait(5000);
                if (acceptTcpClientAsync.IsCompleted)
                {
                    using (TcpClient client = acceptTcpClientAsync.Result)
                    {
                        using (StreamReader reader = new StreamReader(client.GetStream(), Encoding.UTF8))
                        {
                            string actual;
                            actual = reader.ReadLine();
                            return actual;
                        }

                    }
                }
                else
                {
                    return null;
                }
            }
            finally
            {
                listener?.Stop();
            }
        }
开发者ID:mariog86,项目名称:PointOfSale,代码行数:32,代码来源:PointOfSaleTest.cs

示例12: Run

        public void Run()
        {
            if (_disposed)
            {
                throw new InvalidOperationException("Cannot run disposed server");
            }
            _server = new TcpListener(_host, _port);

            // Start listening for client requests.
            _server.Start();
            _running = true;
            Task.Run(async () =>
            {
                while (_running)
                {
                    var tcpClient = await _server.AcceptTcpClientAsync();
                    var cancelTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5)); // todo configuration
                    var task = Task.Run(async () =>
                    {
                        var source = tcpClient.GetStream();
                        var lines = await new LineParser().Parse(source, cancelTokenSource.Token);
                        var httpRequest = HttpRequest.Parse(lines);
                        var responseChannel = new HttpResponseChannel(tcpClient);
                        var httpContext = new HttpContext(httpRequest, responseChannel, cancelTokenSource.Token);
                        _handler(httpContext);
                    }, cancelTokenSource.Token);
                }
            });
        }
开发者ID:momo3038,项目名称:BrowserLog,代码行数:29,代码来源:HttpServer.cs

示例13: SocketConfiguration_applied_to_TcpSocket_when_connecting

        public void SocketConfiguration_applied_to_TcpSocket_when_connecting(NodeType nodeType, bool hasReceiveTimeout)
        {
            var endpoint = TestHelpers.CreateEndpointForTransport(RedFoxTransport.Tcp);
            var socketConfiguration = new SocketConfiguration
            {
                ConnectTimeout = TimeSpan.FromSeconds(5),
                SendBufferSize = 128,
                ReceiveBufferSize = 256,
                SendTimeout = TimeSpan.FromSeconds(1),
                ReceiveTimeout = TimeSpan.FromSeconds(2)
            };

            var server = new TcpListener(IPAddress.Loopback, endpoint.Port);
            server.Start();
            try
            {
                server.AcceptTcpClientAsync();

                var socket = (TcpSocket)new SocketFactory().CreateAndConnectAsync(endpoint, nodeType, socketConfiguration);

                Assert.AreEqual(socketConfiguration.SendBufferSize, socket.TcpClient.SendBufferSize);
                Assert.AreEqual(socketConfiguration.ReceiveBufferSize, socket.TcpClient.ReceiveBufferSize);
                Assert.AreEqual(socketConfiguration.SendTimeout.ToMillisOrZero(), socket.TcpClient.SendTimeout);
                var expectedReceiveTimeout = hasReceiveTimeout ? socketConfiguration.ReceiveTimeout.ToMillisOrZero() : 0;
                Assert.AreEqual(expectedReceiveTimeout, socket.TcpClient.ReceiveTimeout);
            }
            finally
            {
                server.Stop();
            }
        }
开发者ID:tleviathan,项目名称:redfoxmq,代码行数:31,代码来源:SocketFactoryTests.cs

示例14: Start

        public async void Start()
        {
            recorder.StartRecording();

            var ipAdresses = Dns.GetHostEntry("localhost");
            this.IPAddress =
                ipAdresses.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork) ??
                ipAdresses.AddressList.First();

            listener = new TcpListener(this.IPAddress, 5050);
            listener.Start();

            IsActive = true;
            while (IsActive)
            {
                var dTask = Task.Delay(1000);
                var sTask = listener.AcceptTcpClientAsync();

                var t = await Task.WhenAny(dTask, sTask);

                if (t == sTask)
                {
                    ProcessResult(sTask.Result);
                }

                if (terminate)
                {
                    IsActive = false;
                }
            }
        }
开发者ID:duszekmestre,项目名称:MoN.Messenger,代码行数:31,代码来源:AudioServer.cs

示例15: initialize

        public override async void initialize()
        {
            log.Info("Setting up for AddonManager.");
            isWaitingForClient = true;

            try
            {
                listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 0);
                listener.Start();
                port = ((IPEndPoint)listener.LocalEndpoint).Port;

                log.Info(String.Format("Successfully setup AddonManager IPC Talk on port {0}.", port));

                client = await listener.AcceptTcpClientAsync();
                log.Info("Accepted AddonManager client.");

                isAddonManagerRunning = true;
                isWaitingForClient = false;

                cts = new CancellationTokenSource();
                ct = cts.Token;

                stream = client.GetStream();
                client.Client.NoDelay = true;
                client.NoDelay = true;

                listenLoop();
            }
            catch (ObjectDisposedException ex)
            {
                log.Warn("Shutdown of IPC Talk is requested while waiting a client connection from AddonManager.", ex);
            }
        }
开发者ID:berkay2578,项目名称:nfsw-server,代码行数:33,代码来源:AddonManagerTalk.cs


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