コード例 #1
0
 protected override async Task Start(IPEndPoint ipEndpoint)
 {
     thread   = new UvThread();
     listener = new UvTcpListener(thread, ipEndpoint);
     listener.OnConnection(async connection => { await ProcessConnection(connection); });
     await listener.StartAsync();
 }
コード例 #2
0
ファイル: SocketsFacts.cs プロジェクト: tmds/corefxlab
        public async Task RunStressPingPongTest_Libuv()
        {
            var endpoint = new IPEndPoint(IPAddress.Loopback, 5040);

            using (var thread = new UvThread())
                using (var server = new UvTcpListener(thread, endpoint))
                {
                    server.OnConnection(PongServer);
                    await server.StartAsync();

                    const int SendCount = 500, ClientCount = 5;
                    for (int loop = 0; loop < ClientCount; loop++)
                    {
                        using (var connection = await new UvTcpClient(thread, endpoint).ConnectAsync())
                        {
                            try
                            {
                                var tuple = await PingClient(connection, SendCount);

                                Assert.Equal(SendCount, tuple.Item1);
                                Assert.Equal(SendCount, tuple.Item2);
                                Console.WriteLine($"Ping: {tuple.Item1}; Pong: {tuple.Item2}; Time: {tuple.Item3}ms");
                            }
                            finally
                            {
                                await connection.DisposeAsync();
                            }
                        }
                    }
                }
        }
コード例 #3
0
 public void Start(IPEndPoint endpoint, Func <IDuplexPipe, Task> callback)
 {
     _uvThread = new UvThread();
     _listener = new UvTcpListener(_uvThread, endpoint);
     _listener.OnConnection((c) => callback(c));
     _listener.StartAsync().GetAwaiter().GetResult();
 }
コード例 #4
0
 public void Stop()
 {
     listener?.Stop();
     thread?.Dispose();
     listener = null;
     thread   = null;
 }
コード例 #5
0
        public override void Dispose()
        {
            _uvTcpListener?.Dispose();
            _uvThread?.Dispose();

            _uvTcpListener = null;
            _uvThread      = null;
        }
コード例 #6
0
 public void Stop()
 {
     CloseAllConnections();
     listener?.Stop();
     thread?.Dispose();
     listener = null;
     thread   = null;
 }
コード例 #7
0
 public void Start(IPAddress ip, int port)
 {
     if (listener == null)
     {
         thread   = new UvThread();
         listener = new UvTcpListener(thread, new IPEndPoint(ip, port));
         listener.OnConnection(OnConnection);
         listener.Start();
     }
 }
コード例 #8
0
ファイル: HttpServer.cs プロジェクト: ericl85/Channels
        private void StartAcceptingLibuvConnections <TContext>(IHttpApplication <TContext> application, IPAddress ip, int port)
        {
            _uvTcpListener = new UvTcpListener(ip, port);
            _uvTcpListener.OnConnection(async connection =>
            {
                await ProcessClient(application, connection.Input, connection.Output);
            });

            _uvTcpListener.Start();
        }
コード例 #9
0
 public void Start(IPEndPoint endpoint)
 {
     if (listener == null)
     {
         thread   = new UvThread();
         listener = new UvTcpListener(thread, endpoint);
         listener.OnConnection(OnConnection);
         listener.Start();
     }
 }
コード例 #10
0
        public void Stop()
        {
            uvThread?.Dispose();
            uvListener = null;
            uvThread   = null;

            socketListener?.Stop();
            socketListener?.Dispose();
            socketListener = null;
        }
コード例 #11
0
 public void StartLibuv(IPAddress ip, int port)
 {
     if (uvListener == null && socketListener == null)
     {
         uvThread   = new UvThread();
         uvListener = new UvTcpListener(uvThread, new IPEndPoint(ip, port));
         uvListener.OnConnection(OnConnection);
         uvListener.Start();
     }
 }
コード例 #12
0
 public Task StartLibuvAsync(IPAddress ip, int port)
 {
     if (uvListener == null && socketListener == null)
     {
         uvThread   = new UvThread();
         uvListener = new UvTcpListener(uvThread, new IPEndPoint(ip, port));
         uvListener.OnConnection(OnConnection);
         return(uvListener.StartAsync());
     }
     return(Task.CompletedTask);
 }
コード例 #13
0
ファイル: HttpServer.cs プロジェクト: yizhang82/corefxlab
        private void StartAcceptingLibuvConnections <TContext>(IHttpApplication <TContext> application, IPAddress ip, int port)
        {
            _uvThread      = new UvThread();
            _uvTcpListener = new UvTcpListener(_uvThread, new IPEndPoint(ip, port));
            _uvTcpListener.OnConnection(async connection =>
            {
                await ProcessClient(application, connection);
            });

            _uvTcpListener.StartAsync();
        }
コード例 #14
0
ファイル: HttpServer.cs プロジェクト: yizhang82/corefxlab
        public void Dispose()
        {
            _rioTcpServer?.Stop();
            _listenSocket?.Dispose();
            _uvTcpListener?.Dispose();
            _uvThread?.Dispose();

            _rioTcpServer  = null;
            _listenSocket  = null;
            _uvTcpListener = null;
            _uvThread      = null;
        }
コード例 #15
0
        private static void RunServerForNode()
        {
            UvThread      uvThread = new UvThread();
            var           ip       = IPAddress.Any;
            UvTcpListener listener = new UvTcpListener(uvThread, new IPEndPoint(ip, port));

            listener.OnConnection(async connection =>
            {
                Interlocked.Increment(ref connectionCounter);
                var input  = connection.Input;
                var output = connection.Output;
                var flag   = false;

                //Used for stop sending info to connected client.
                await Task.Factory.StartNew(async() =>
                {
                    //Wait for client disconnection.
                    var result = await input.ReadAsync();
                    flag       = true;
                });

                while (!flag)
                {
                    try
                    {
                        WritableBuffer oBuffer = output.Alloc();
                        oBuffer.WriteUtf8String(DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss:ms"));
                        await oBuffer.FlushAsync();
                        Interlocked.Increment(ref sendCounter);
                        await Task.Delay(r.Next(0, 500));
                    }
                    catch (Exception e)
                    {
                        break;
                    }
                }
            });

            listener.Start();

            var pid = System.Diagnostics.Process.GetCurrentProcess().Id;

            Console.WriteLine($"Listening on {ip} on port {port} / PID {pid}");
            Console.ReadKey();

            listener.Stop();
            uvThread.Dispose();
        }
コード例 #16
0
ファイル: SocketsFacts.cs プロジェクト: mramosMS/corefxlab
        public async Task CanCreateWorkingEchoServer_PipelineLibuvServer_NonPipelineClient()
        {
            var          endpoint      = new IPEndPoint(IPAddress.Loopback, 5010);
            const string MessageToSend = "Hello world!";
            string       reply         = null;

            using (var thread = new UvThread())
                using (var server = new UvTcpListener(thread, endpoint))
                {
                    server.OnConnection(Echo);
                    await server.StartAsync();

                    reply = SendBasicSocketMessage(endpoint, MessageToSend);
                }
            Assert.Equal(MessageToSend, reply);
        }
コード例 #17
0
        private static void TestOpenAndCloseListener()
        {
            var thread   = new UvThread();
            var ep       = new IPEndPoint(IPAddress.Loopback, 5003);
            var listener = new UvTcpListener(thread, ep);

            listener.OnConnection(_ => Console.WriteLine("Hi and bye"));
            listener.Start();
            Console.WriteLine("Listening...");
            Thread.Sleep(1000);
            Console.WriteLine("Stopping listener...");
            listener.Stop();
            Thread.Sleep(1000);
            Console.WriteLine("Disposing thread...");
            thread.Dispose();
        }
コード例 #18
0
        private static void Start()
        {
            var thread   = new UvThread();
            var listener = new UvTcpListener(thread, new IPEndPoint(IPAddress.Any, 5000));

            listener.OnConnection(async connection =>
            {
                while (true)
                {
                    // Wait for data
                    var result   = await connection.Input.ReadAsync();
                    var input    = result.Buffer;
                    var consumed = input.Start;

                    if (input.IsEmpty && result.IsCompleted)
                    {
                        // No more data
                        if (s_trace)
                        {
                            Console.WriteLine("Connection closed by client");
                        }

                        break;
                    }

                    if (s_trace)
                    {
                        Console.WriteLine($"Received {input.Length} bytes");
                    }

                    // Send response
                    var output = connection.Output.Alloc(s_responseMessage.Length);
                    s_responseMessage.CopyTo(output.Buffer);
                    output.Advance(s_responseMessage.Length);
                    await output.FlushAsync();

                    // Consume the input
                    consumed = input.Move(consumed, input.Length);
                    connection.Input.Advance(consumed, consumed);
                }
            });

            listener.StartAsync().GetAwaiter().GetResult();
        }
コード例 #19
0
        //[Fact]
        public void CanCreateWorkingEchoServer_ChannelLibuvServer_NonChannelClient()
        {
            var          endpoint      = new IPEndPoint(IPAddress.Loopback, 5010);
            const string MessageToSend = "Hello world!";
            string       reply         = null;

            using (var thread = new UvThread())
            {
                var server = new UvTcpListener(thread, endpoint);
                server.OnConnection(Echo);
                server.Start();
                try
                {
                    reply = SendBasicSocketMessage(endpoint, MessageToSend);
                }
                finally
                {
                    server.Stop();
                }
            }
            Assert.Equal(MessageToSend, reply);
        }
コード例 #20
0
        public Task Run()
        {
            var ip       = IPAddress.Any;
            int port     = 5000;
            var thread   = new UvThread();
            var listener = new UvTcpListener(thread, new IPEndPoint(ip, port));

            listener.OnConnection(async connection =>
            {
                var pipelineConnection = MakePipeline(connection);

                var decoder = new LineDecoder();
                var handler = new LineHandler();

                // Initialize the handler with the connection
                handler.Initialize(pipelineConnection);

                try
                {
                    while (true)
                    {
                        // Wait for data
                        var result = await pipelineConnection.Input.ReadAsync();
                        var input  = result.Buffer;

                        try
                        {
                            if (input.IsEmpty && result.IsCompleted)
                            {
                                // No more data
                                break;
                            }

                            while (decoder.TryDecode(ref input, out Line line))
                            {
                                await handler.HandleAsync(line);
                            }

                            if (!input.IsEmpty && result.IsCompleted)
                            {
                                // Didn't get the whole frame and the connection ended
                                throw new EndOfStreamException();
                            }
                        }
                        finally
                        {
                            // Consume the input
                            pipelineConnection.Input.Advance(input.Start, input.End);
                        }
                    }
                }
                finally
                {
                    // Close the input, which will tell the producer to stop producing
                    pipelineConnection.Input.Complete();

                    // Close the output, which will close the connection
                    pipelineConnection.Output.Complete();
                }
            });

            listener.StartAsync().GetAwaiter().GetResult();

            Console.WriteLine($"Listening on {ip} on port {port}");
            Console.ReadKey();

            listener.Dispose();
            thread.Dispose();
            return(Task.CompletedTask);
        }
コード例 #21
0
 public void Stop()
 {
     _listener.Dispose();
     _listener = null;
     _uvThread = null;
 }
コード例 #22
0
        public static void Run()
        {
            var ip       = IPAddress.Any;
            int port     = 5000;
            var thread   = new UvThread();
            var listener = new UvTcpListener(thread, new IPEndPoint(ip, port));

            listener.OnConnection(async connection =>
            {
                var channel = MakePipeline(connection);

                var decoder = new LineDecoder();
                var handler = new LineHandler();

                // Initialize the handler with the channel
                handler.Initialize(channel);

                try
                {
                    while (true)
                    {
                        // Wait for data
                        var input = await channel.Input.ReadAsync();

                        try
                        {
                            if (input.IsEmpty && channel.Input.Reading.IsCompleted)
                            {
                                // No more data
                                break;
                            }

                            Line line;
                            if (!decoder.TryDecode(ref input, out line))
                            {
                                if (channel.Input.Reading.IsCompleted)
                                {
                                    // Didn't get the whole frame and the connection ended
                                    throw new EndOfStreamException();
                                }

                                // Need more data
                                continue;
                            }

                            await handler.HandleAsync(line);
                        }
                        finally
                        {
                            // Consume the input
                            channel.Input.Advance(input.Start, input.End);
                        }
                    }
                }
                finally
                {
                    // Close the input channel, which will tell the producer to stop producing
                    channel.Input.Complete();

                    // Close the output channel, which will close the connection
                    channel.Output.Complete();
                }
            });

            listener.Start();

            Console.WriteLine($"Listening on {ip} on port {port}");
            Console.ReadKey();

            listener.Stop();
            thread.Dispose();
        }
コード例 #23
0
        public static void Run()
        {
            var ip       = IPAddress.Any;
            int port     = 5000;
            var thread   = new UvThread();
            var listener = new UvTcpListener(thread, new IPEndPoint(ip, port));

            listener.OnConnection(async connection =>
            {
                var httpParser = new HttpRequestParser();

                while (true)
                {
                    // Wait for data
                    var result   = await connection.Input.ReadAsync();
                    var input    = result.Buffer;
                    var consumed = input.Start;
                    var examined = input.Start;

                    try
                    {
                        if (input.IsEmpty && result.IsCompleted)
                        {
                            // No more data
                            break;
                        }

                        // Parse the input http request
                        var parseResult = httpParser.ParseRequest(input, out consumed, out examined);

                        switch (parseResult)
                        {
                        case HttpRequestParser.ParseResult.Incomplete:
                            if (result.IsCompleted)
                            {
                                // Didn't get the whole request and the connection ended
                                throw new EndOfStreamException();
                            }
                            // Need more data
                            continue;

                        case HttpRequestParser.ParseResult.Complete:
                            break;

                        case HttpRequestParser.ParseResult.BadRequest:
                            throw new Exception();

                        default:
                            break;
                        }

                        // Writing directly to pooled buffers
                        var output    = connection.Output.Alloc();
                        var formatter = new OutputFormatter <WritableBuffer>(output, TextEncoder.Utf8);
                        formatter.Append("HTTP/1.1 200 OK");
                        formatter.Append("\r\nContent-Length: 13");
                        formatter.Append("\r\nContent-Type: text/plain");
                        formatter.Append("\r\n\r\n");
                        formatter.Append("Hello, World!");
                        await output.FlushAsync();

                        httpParser.Reset();
                    }
                    finally
                    {
                        // Consume the input
                        connection.Input.Advance(consumed, examined);
                    }
                }
            });

            listener.StartAsync().GetAwaiter().GetResult();

            Console.WriteLine($"Listening on {ip} on port {port}");
            var wh = new ManualResetEventSlim();

            Console.CancelKeyPress += (sender, e) =>
            {
                wh.Set();
            };

            wh.Wait();

            listener.Dispose();
            thread.Dispose();
        }