AcceptTcpClientAsync() публичный Метод

public AcceptTcpClientAsync ( ) : Task
Результат Task
        public async Task CertificateValidationClientServer_EndToEnd_Ok()
        {
            IPEndPoint endPoint = new IPEndPoint(IPAddress.IPv6Loopback, 0);
            var server = new TcpListener(endPoint);
            server.Start();

            using (var clientConnection = new TcpClient(AddressFamily.InterNetworkV6))
            {
                IPEndPoint serverEndPoint = (IPEndPoint)server.LocalEndpoint;

                Task clientConnect = clientConnection.ConnectAsync(serverEndPoint.Address, serverEndPoint.Port);
                Task<TcpClient> serverAccept = server.AcceptTcpClientAsync();

                Assert.True(
                    Task.WaitAll(
                        new Task[] { clientConnect, serverAccept }, 
                        TestConfiguration.TestTimeoutSeconds * 1000),
                    "Client/Server TCP Connect timed out.");

                using (TcpClient serverConnection = await serverAccept)
                using (SslStream sslClientStream = new SslStream(
                    clientConnection.GetStream(),
                    false,
                    ClientSideRemoteServerCertificateValidation))
                using (SslStream sslServerStream = new SslStream(
                    serverConnection.GetStream(),
                    false,
                    ServerSideRemoteClientCertificateValidation))

                {
                    string serverName = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false);
                    string clientName = _clientCertificate.GetNameInfo(X509NameType.SimpleName, false);

                    var clientCerts = new X509CertificateCollection();
                    clientCerts.Add(_clientCertificate);

                    Task clientAuthentication = sslClientStream.AuthenticateAsClientAsync(
                        serverName,
                        clientCerts,
                        TestConfiguration.DefaultSslProtocols,
                        false);

                    Task serverAuthentication = sslServerStream.AuthenticateAsServerAsync(
                        _serverCertificate,
                        true,
                        TestConfiguration.DefaultSslProtocols,
                        false);

                    Assert.True(
                        Task.WaitAll(
                            new Task[] { clientAuthentication, serverAuthentication }, 
                            TestConfiguration.TestTimeoutSeconds * 1000),
                        "Client/Server Authentication timed out.");
                }
            }
        }
        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;
        }
Пример #3
1
 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);
 }
Пример #4
0
        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();
        }
Пример #5
0
        /// <summary>
        /// Accept Connections
        /// </summary>
        /// <returns></returns>
        private async Task AcceptConnections()
        {
            listener = new TcpListener(Server.Address, Server.Port);
            var bufferSize = Buffer; // Get the current buffer size on start
            listener.Start();
            Running = true;

            // If there is an exception we want to output the message to the console for debugging
            try
            {
                // While the Running bool is true, the listener is not null and there is no cancellation requested
                while (Running && listener != null && !cancellationTokenSource.Token.IsCancellationRequested)
                {
                    var client = await listener.AcceptTcpClientAsync().WithWaitCancellation(cancellationTokenSource.Token);
                    if (client != null)
                    {
                        // Proxy the data from the client to the server until the end of stream filling the buffer.
                        await ProxyClientConnection(client, bufferSize);
                    }

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            listener.Stop();
        }
Пример #6
0
        /// <summary>
        /// Starts up the server and begins listening for connections
        /// </summary>
        internal async void Start()
        {
            IPAddress ipAddre = IPAddress.Loopback;
            TcpListener listener = new TcpListener(ipAddre, _port);
            listener.Start();
            LogMessage("Server is running");
            LogMessage("Listening on port " + _port);

            this.Running = true;

            while (true)
            {
                LogMessage("Waiting for connections...");
                try
                {
                    var tcpClient = await listener.AcceptTcpClientAsync();
                    HandleConnectionAsync(tcpClient);
                }
                catch (Exception exp)
                {
                    LogMessage(exp.ToString());
                }

            }
        }
Пример #7
0
        public void Run()
        {
            WNSAuthentication.Instance.AuthenticateWithWNS();

            Logger.Info($"Starting TCP listener on port {Port}");
            var listener = new TcpListener(IPAddress.Any, Port);
            listener.Start();

            Logger.Info($"Starting heartbeat timer with interval {_heartBeatTimer.Interval}");
            _heartBeatTimer.Start();


            Task.Run(async () =>
            {
                while (true)
                {
                    try
                    {
                        HandleNewConnection(await listener.AcceptTcpClientAsync());
                    }
                    catch (Exception ex)
                    {
                        Logger.Fatal("Exception occred when creating a new client session", ex);
                    }
                }
            });
        }
Пример #8
0
 /// <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.");
         }
     });
 }
Пример #9
0
        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();
            }
        }
Пример #10
0
        public async void ListenAsync(string ip, int port)
        {
            if (Listening)
            {
                throw new Exception("Listening");
            }
            Listening = true;

            server = new System.Net.Sockets.TcpListener(IPAddress.Parse(ip), port);
            server.Start();
            ListeningStarted(this, server);
            Env.Print($"listening: {server.LocalEndpoint.ToString()}");
            try
            {
                while (true)
                {
                    Env.Print("waiting for a connection");
                    var client = await server.AcceptTcpClientAsync();

                    Env.Print("one incoming tcp connection");

                    var session = new TcpClientSession(client);
                    NewSession.Invoke(this, session);
                    TcpClientAccepted?.Invoke(this, session);
                    session.Receive();
                }
            }
            catch (Exception ex)
            {
                Env.Print(ex.Message);
            }
        }
Пример #11
0
        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);
                }
            });
        }
Пример #12
0
        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();
            }
        }
Пример #13
0
        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;
                }
            }
        }
Пример #14
0
        private async void buttonConnect_Click(object sender, RibbonControlEventArgs e)
        {
            if (!string.IsNullOrEmpty(comboBoxIp.Text))
            {
                try {

                    if (listner != null)
                    {
                        listner.Stop();
                        listner = null;
                    }
                    listner = new TcpListener(IPAddress.Parse(comboBoxIp.Text),port);
                    listner.Start();
                    labelStatus.Label = "データ待機中";
                    client = await listner.AcceptTcpClientAsync();
                    stream = client.GetStream();
                    byte[] buff = new byte[1];
                    var read = await stream.ReadAsync(buff, 0, buff.Length);
                    ExecuteCommand(buff[0]);
                    
                    
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("IPを選択してください");
            }

        }
Пример #15
0
        /// <summary>
        /// Starts accepting connections.
        /// </summary>
        public void Start()
        {
            if (disposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }

            // This is equivalent to the behavior of TcpListener.Create in .NET 4.5.
            listener = new Net.TcpListener(IPAddress.Any, port);
            //listener.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 0);

            listener.Start();


            listenerSubscription = Observable
                                   .FromAsync(() => listener.AcceptTcpClientAsync())
                                   .Repeat()
                                   .Select(client => new ReactiveSocket(client))
                                   .Subscribe(socket =>
            {
                connections.Add(socket);
                observable.OnNext(socket);

                IDisposable disposeSubscription = Observable.FromEventPattern <EventHandler, EventArgs>(
                    h => socket.Disposed       += h, h => socket.Disposed -= h)
                                                  .FirstAsync().Subscribe(x =>
                {
                    connections.Remove(socket);
                });

                this.socketDisposable.Add(disposeSubscription);
            });
        }
Пример #16
0
        // http://stackoverflow.com/questions/7690520/c-sharp-networking-tcpclient
        void TcpListenerLoop()
        {
            try
            {
                m_tcpListener = new System.Net.Sockets.TcpListener(IPAddress.Parse(m_privateIP), m_port);  
                m_tcpListener.Start();
                Console.WriteLine($"*TcpListener is listening on port {m_privateIP}:{m_port}.");
                while (true)
                {
                    var tcpListenerCurrentClientTask = m_tcpListener.AcceptTcpClientAsync();
                    var tcpClient = tcpListenerCurrentClientTask.Result;        // Task.Result is blocking. OK.
                    Console.WriteLine($"TcpListenerLoop.NextClientAccepted.");
                    Utils.Logger.Info($"TcpListenerLoop.NextClientAccepted.");
                    if (Utils.MainThreadIsExiting.IsSet)
                        return; // if App is exiting gracefully, don't start new thread

                    m_tcpClientQueue.Add(tcpClient);     // If it is a long processing, e.g. reading the TcpClient, do it in a separate thread. If it is just added to the queue, don't start a new thread
                    //(new Thread((x) => ReadTcpClientStream(x)) { IsBackground = true }).Start(tcpClient);    // read the BinaryReader() and deserialize in separate thread, so not block the TcpListener loop
                }
            }
            catch (Exception e) // Background thread can crash application. A background thread does not keep the managed execution environment running.
            {
                if (Utils.MainThreadIsExiting.IsSet)
                    return; // if App is exiting gracefully, this Exception is not a problem
                Utils.Logger.Error("Not expected Exception. We send email by StrongAssert and rethrow exception, which will crash App. TcpListenerLoop. " + e.Message + " ,InnerException: " + ((e.InnerException != null) ? e.InnerException.Message : ""));
                StrongAssert.Fail(Severity.ThrowException, "Not expected Exception. We send email by StrongAssert and rethrow exception, which will crash App. TcpListenerLoop. VirtualBroker: manual restart is needed.");
                throw;  // if we don't listen to TcpListener any more, there is no point to continue. Crash the App.
            }
        }
        public async Task ReadLineAsync_ThrowsOnConnectionClose()
        {
            TcpListener listener = new TcpListener(IPAddress.Loopback, 0);

            try
            {
                listener.Start();
                Task<TcpClient> acceptTask = listener.AcceptTcpClientAsync();

                TcpClient client = new TcpClient();
                await client.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port);

                using (TcpClient serverTcpClient = await acceptTask)
                {
                    TcpClientConnectionChannel channel = new TcpClientConnectionChannel(serverTcpClient);
                    client.Dispose();

                    await Assert.ThrowsAsync<ConnectionUnexpectedlyClosedException>(async () =>
                    {
                        await channel.ReadLineAsync();
                    });
                }
            }
            finally
            {
                listener.Stop();
            }
        }
Пример #18
0
 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));
     }
 }
        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();
            }
        }
Пример #20
0
        public async Task Start(IPAddress iP, int port)
        {
            tcpListener = new TcpListener(iP, port);

            connectedTcpClient = null;
            source             = new CancellationTokenSource();
            token = source.Token;

            tcpListener.Start();

            EventHandler serverStartedHandler = ServerStarted;

            if (serverStartedHandler != null)
            {
                serverStartedHandler(this, null);
            }

            connectedTcpClient = await Task.Run(() => tcpListener.AcceptTcpClientAsync(), token);

            if (connectedTcpClient != null)
            {
                EventHandler clientConnectedHandler = ClientConnected;
                if (clientConnectedHandler != null)
                {
                    clientConnectedHandler(this, null);
                }

                var c = new Thread(() => ServerReceive());
                c.Start();
            }
        }
Пример #21
0
        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);
        }
Пример #22
0
        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.");
            }
        }
Пример #23
0
        public async Task Start(string remoteServerIp, ushort remoteServerPort, ushort localPort, string localIp)
        {
            //var clients = new ConcurrentDictionary<IPEndPoint, TcpClient>();

            IPAddress localIpAddress = string.IsNullOrEmpty(localIp) ? IPAddress.IPv6Any : IPAddress.Parse(localIp);
            var       server         = new System.Net.Sockets.TcpListener(new IPEndPoint(localIpAddress, localPort));

            server.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
            server.Start();

            Console.WriteLine($"TCP proxy started {localPort} -> {remoteServerIp}|{remoteServerPort}");
            while (true)
            {
                try
                {
                    var remoteClient = await server.AcceptTcpClientAsync();

                    remoteClient.NoDelay = true;


                    new TcpClient(remoteClient, new IPEndPoint(IPAddress.Parse(remoteServerIp), remoteServerPort));
                }
                catch (Exception) { }
            }
        }
Пример #24
0
        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);
            }
        }
Пример #25
0
        public static async Task AcceptClientsAsync(TcpListener listener, CancellationToken cancel)
        {
            await Task.Yield();

            while (!cancel.IsCancellationRequested)
            {
                try
                {
                    var timeoutTask = Task.Delay(2000);
                    var acceptTask = listener.AcceptTcpClientAsync();

                    await Task.WhenAny(timeoutTask, acceptTask);
                    if (!acceptTask.IsCompleted)
                        continue;

                    var client = await acceptTask;
                    HandleClientAsync(client, cancel);
                }
                catch (Exception aex)
                {
                    var ex = aex.GetBaseException();
                    Console.WriteLine("Accepting error: " + ex.Message);
                }
            }
        }
        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();
        }
        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();
        }
Пример #28
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Server start");
            int port = 55555;
            var listener = new TcpListener(IPAddress.Loopback, port);
            listener.Start();
            Console.WriteLine("start listening");

            var client = listener.AcceptTcpClientAsync().Result;
            var stream = client.GetStream();

            var reader = new StreamReader(stream);
            
            Console.WriteLine("Connected");
            
            var data = reader.ReadLine();

            if (data == null) {
                Console.WriteLine("data is null");
            } 
            else 
            {
                Console.WriteLine(data);
            }            
        }
Пример #29
0
        public async Task Start(string remoteServerIp, ushort remoteServerPort, ushort localPort, string localIp, byte[] byteMapClient2Setver, byte[] byteMapSetver2Client)
        {
            //var clients = new ConcurrentDictionary<IPEndPoint, TcpClient>();

            IPAddress localIpAddress = string.IsNullOrEmpty(localIp) ? IPAddress.IPv6Any : IPAddress.Parse(localIp);
            var       server         = new System.Net.Sockets.TcpListener(new IPEndPoint(localIpAddress, localPort));

            server.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
            server.Start();

            Console.WriteLine($"TCP proxy started {localPort} -> {remoteServerIp}|{remoteServerPort}");
            while (true)
            {
                try
                {
                    var remoteClient = await server.AcceptTcpClientAsync();

                    remoteClient.NoDelay = true;
                    var ips = await Dns.GetHostAddressesAsync(remoteServerIp);

                    new TcpClient(remoteClient, new IPEndPoint(ips.First(), remoteServerPort), byteMapClient2Setver, byteMapSetver2Client);
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(ex);
                    Console.ResetColor();
                }
            }
        }
Пример #30
0
 public static async Task ProcessAsync(TcpListener server)
 {
     var tcpClient = await server.AcceptTcpClientAsync();
     using (var stream = tcpClient.GetStream())
     {
         await TcpMessenger.ReadAndWriteAsync(stream, Constants.ClientToServer, Constants.ServerToClient);
     }
 }
Пример #31
0
        public async void SslStream_SendReceiveOverNetworkStream_Ok()
        {
            TcpListener listener = new TcpListener(IPAddress.Any, 0);

            using (X509Certificate2 serverCertificate = Configuration.Certificates.GetServerCertificate())
            using (TcpClient client = new TcpClient())
            {
                listener.Start();

                Task clientConnectTask = client.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port);
                Task<TcpClient> listenerAcceptTask = listener.AcceptTcpClientAsync();

                await Task.WhenAll(clientConnectTask, listenerAcceptTask);

                TcpClient server = listenerAcceptTask.Result;
                using (SslStream clientStream = new SslStream(
                    client.GetStream(),
                    false,
                    new RemoteCertificateValidationCallback(ValidateServerCertificate),
                    null,
                    EncryptionPolicy.RequireEncryption))
                using (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);

                    await Task.WhenAll(clientAuthenticationTask, serverAuthenticationTask);

                    byte[] readBuffer = new byte[256];
                    Task<int> readTask = clientStream.ReadAsync(readBuffer, 0, readBuffer.Length);

                    byte[] writeBuffer = new byte[256];
                    Task writeTask = clientStream.WriteAsync(writeBuffer, 0, writeBuffer.Length);

                    bool result = Task.WaitAll(
                        new Task[1] { writeTask }, 
                        TestConfiguration.PassingTestTimeoutMilliseconds);

                    Assert.True(result, "WriteAsync timed-out.");
                }
            }
        }
Пример #32
0
        public void Start()
        {
            _tcpListener = new TcpListener(IPAddress.Any, 4444);
            _tcpListener.Start();
            _tcpListener.AcceptTcpClientAsync().ContinueWith(TcpClientConnected);

            _pollSocketsThread = new Thread(_connectionService.PollConnectedUsersForUpdates);
            _pollSocketsThread.Start();
        }
Пример #33
0
 private async Task AcceptClients(TcpListener listener)
 {
     while (m_Listen)
     {
         var client = await listener.AcceptTcpClientAsync();
         m_ReceivingTasks.Add(ReceiveMessages(client));
         InvokeConnected(client);
         m_Clients.Add(client);
     }
 }
Пример #34
0
        /// <summary>
        /// Accept connections
        /// </summary>
        /// <returns></returns>
        private async Task AcceptConnections()
        {
            listener = new TcpListener(Server.Address, Server.Port);
            var bufferSize = Buffer; // Get the current buffer size on start
            listener.Start();
            Running = true;

            // If there is an exception we want to output the message to the console for debugging
            try
            {
                // While the Running bool is true, the listener is not null and there is no cancellation requested
                while (Running && listener != null && !cancellationTokenSource.Token.IsCancellationRequested)
                {
                    var client = await listener.AcceptTcpClientAsync().WithWaitCancellation(cancellationTokenSource.Token);
                    if (client != null)
                    {

                        if (ClientList.Count(definition => definition.ServerEndPoint == client.Client.LocalEndPoint) == 0)
                        {
                            var oldClients = ClientList.Where(definition => definition.ServerEndPoint == client.Client.LocalEndPoint)
                                    .ToList();
                            foreach (var vncRepeaterDefinition in oldClients)
                            {
                                ClientList.Remove(vncRepeaterDefinition);
                            }
                        }

                        // Proxy the data from the client to the server until the end of stream filling the buffer.
                        if (ClientList.Count(definition => definition.ServerEndPoint == client.Client.LocalEndPoint) == 0)
                        {
                            var definition = new VNCRepeaterDefinition()
                            {
                                Authenticated = false,
                                FirstRequest = DateTime.UtcNow,
                                ClientEndPoint = (IPEndPoint)client.Client.RemoteEndPoint,
                                ServerEndPoint = (IPEndPoint)client.Client.LocalEndPoint
                            };

                            this.ClientList.Add(definition);

                            // We havent dealt with this one before.
                            await ProxyClientConnection(client, definition, bufferSize);
                        }

                    }

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            listener.Stop();
        }
 /// <summary>
 /// AcceptTcpClientAsync does not natively support cancellation, so use this wrapper. Make sure
 /// the cancellation token is registered to stop the listener.
 /// </summary>
 /// <remarks>See https://stackoverflow.com/questions/19220957/tcplistener-how-to-stop-listening-while-awaiting-accepttcpclientasync</remarks>
 private async Task <TcpClient> AcceptTcpClientAsync(CancellationToken token)
 {
     try
     {
         return(await _tcpListener.AcceptTcpClientAsync().ConfigureAwait(false));
     }
     catch (Exception ex) when(token.IsCancellationRequested)
     {
         throw new OperationCanceledException("Cancellation was requested while awaiting TCP client connection.", ex);
     }
 }
 private async static Task ServerProcess(TcpListener listener)
 {
     using (TcpClient c = await listener.AcceptTcpClientAsync())
     using (NetworkStream networkstream = c.GetStream())
     {
         string ControlCode = Encoding.UTF8.GetString(await ReadMessage(networkstream));
         RxLedStatus();
         DeviceControl.DeviceOperation(ControlCode);
         Data.Source.Msg("\nModuleTcpServer client control code: " + ControlCode);
     }
 }
Пример #37
0
        private void ListenForClientsProc(CancellationTokenSource cts)
        {
            IsListeningChanged?.Invoke(true);
            try
            {
                while (!cts.Token.IsCancellationRequested && (_server != null))
                {
                    System.Threading.Thread.Sleep(1);
                    if (IsListening && !_server.Pending())
                    {
                        continue;
                    }

                    TcpClient client = null;
                    try
                    {
                        client = _server.AcceptTcpClientAsync().Result;
                    }
                    catch (NullReferenceException)
                    {
                        break;
                    }
                    catch (ObjectDisposedException)
                    {
                        break;
                    }
                    catch (SocketException e)
                    {
                        if (e.SocketErrorCode != SocketError.Interrupted) //the server was stopped
                        {
                            Log.e("SocketException: Socket Error Code {0}: {1}\n{2}", e.SocketErrorCode,
                                  Enum.GetName(typeof(System.Net.Sockets.SocketError), e.SocketErrorCode),
                                  e.ToString());
                        }
                        break;
                    }
                    catch (Exception e)
                    {
                        Log.e(e);
                        break;
                    }
                    OnCreateClientHandler(client);
                }
            }
            catch (Exception e)
            {
                Log.e(e);
            }
            finally
            {
                IsListening = false;
                IsListeningChanged?.Invoke(IsListening);
            }
        }
Пример #38
0
        // BCL Tcp Server
        public static async Task BclServer()
        {
            var listener = new System.Net.Sockets.TcpListener(Default.IPEndPoint);

            try {
                listener.Start();
                using (var client = await listener.AcceptTcpClientAsync()) {
                    var sr      = new StreamReader(client.GetStream());
                    var message = await sr.ReadToEndAsync();

                    Console.WriteLine("BCL: " + message);
                }
            } finally {
                listener.Stop();
            }
        }
Пример #39
0
 private static void Listen(object state)
 {
     if (_listener.Pending())
     {
         Broadcast(_listener, new MessageEventArgs(new Message("Connection Found.")));
         System.Net.Sockets.TcpClient client = (System.Net.Sockets.TcpClient)_listener.AcceptTcpClientAsync().AsyncState;
         if (client != null)
         {
             NetworkStream ns    = client.GetStream();
             byte[]        bytes = new byte[256];
             string        data;
             int           i;
             while ((i = ns.Read(bytes, 0, bytes.Length)) != 0)
             {
                 data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                 Broadcast(_listener, new MessageEventArgs(new Message(data)));
             }
             client.Dispose();
         }
     }
 }
Пример #40
0
        private async void InitListener()
        {
            var tcpServer = new Sockets.TcpListener(IPAddress.Any, ClientListenerPort);

            tcpServer.Start();

            while (true)
            {
                tcpReciever = await tcpServer.AcceptTcpClientAsync();

                var stream = tcpReciever.GetStream();
                properlyDisconnected = false;

                while (true)
                {
                    var message = TcpUtils.ReadMessage(stream);
                    if (string.IsNullOrEmpty(message))
                    {
                        if (!properlyDisconnected)
                        {
                            Invoke(new Action(() =>
                            {
                                MessageBox.Show(this,
                                                "Соединение с сервером потеряно. Подключение будет закрыто",
                                                "Сервер отключен",
                                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                                Disconnect();
                            }));
                        }
                        break;
                    }

                    message = DateTime.Now.ToString("t") + ": " + message;
                    lbMessages.Invoke(new Action(() => lbMessages.Items.Add(message)));
                }
            }
        }