Beispiel #1
0
        private UvTcpHandle ListenTcp(bool useFileHandle)
        {
            var socket = new UvTcpHandle(Log);

            try
            {
                socket.Init(Thread.Loop, Thread.QueueCloseHandle);
#pragma warning disable CS0618
                socket.NoDelay(TransportContext.Options.NoDelay);
#pragma warning restore CS0618

                if (!useFileHandle)
                {
                    socket.Bind((IPEndPoint)EndPoint);

                    // If requested port was "0", replace with assigned dynamic port.
                    EndPoint = socket.GetSockIPEndPoint();
                }
                else
                {
                    socket.Open((IntPtr)((FileHandleEndPoint)EndPoint).FileHandle);
                }
            }
            catch
            {
                socket.Dispose();
                throw;
            }

            return(socket);
        }
Beispiel #2
0
        private UvTcpHandle ListenTcp(bool useFileHandle)
        {
            var socket = new UvTcpHandle(Log);

            try
            {
                socket.Init(Thread.Loop, Thread.QueueCloseHandle);
                socket.NoDelay(EndPointInformation.NoDelay);

                if (!useFileHandle)
                {
                    socket.Bind(EndPointInformation.IPEndPoint);

                    // If requested port was "0", replace with assigned dynamic port.
                    EndPointInformation.IPEndPoint = socket.GetSockIPEndPoint();
                }
                else
                {
                    socket.Open((IntPtr)EndPointInformation.FileHandle);
                }
            }
            catch
            {
                socket.Dispose();
                throw;
            }

            return(socket);
        }
        private void OnPost()
        {
            _listenSocket.Dispose();

            // Unreference the post handle
            _shutdownPostHandle.Unreference();
        }
        public async Task SocketCanListenAndAccept()
        {
            var loop = new UvLoopHandle(_logger);

            loop.Init(_uv);
            var tcp = new UvTcpHandle(_logger);

            tcp.Init(loop, (a, b) => { });
            var address = ServerAddress.FromUrl($"http://127.0.0.1:0/");

            tcp.Bind(address);
            var port = tcp.GetSockIPEndPoint().Port;

            tcp.Listen(10, (stream, status, error, state) =>
            {
                var tcp2 = new UvTcpHandle(_logger);
                tcp2.Init(loop, (a, b) => { });
                stream.Accept(tcp2);
                tcp2.Dispose();
                stream.Dispose();
            }, null);
            var t = Task.Run(() =>
            {
                var socket = TestConnection.CreateConnectedLoopbackSocket(port);
                socket.Dispose();
            });

            loop.Run();
            loop.Dispose();
            await t;
        }
        public async Task SocketCanRead()
        {
            int bytesRead = 0;
            var loop      = new UvLoopHandle();

            loop.Init(_uv);
            var tcp = new UvTcpHandle();

            tcp.Init(loop);
            tcp.Bind(new IPEndPoint(IPAddress.Loopback, 54321));
            tcp.Listen(10, (_, status, error, state) =>
            {
                Console.WriteLine("Connected");
                var tcp2 = new UvTcpHandle();
                tcp2.Init(loop);
                tcp.Accept(tcp2);
                var data = Marshal.AllocCoTaskMem(500);
                tcp2.ReadStart(
                    (a, b, c) => _uv.buf_init(data, 500),
                    (__, nread, error2, state2) =>
                {
                    bytesRead += nread;
                    if (nread == 0)
                    {
                        tcp2.Dispose();
                    }
                },
                    null);
                tcp.Dispose();
            }, null);
            Console.WriteLine("Task.Run");
            var t = Task.Run(async() =>
            {
                var socket = new Socket(
                    AddressFamily.InterNetwork,
                    SocketType.Stream,
                    ProtocolType.Tcp);
                await Task.Factory.FromAsync(
                    socket.BeginConnect,
                    socket.EndConnect,
                    new IPEndPoint(IPAddress.Loopback, 54321),
                    null,
                    TaskCreationOptions.None);
                await Task.Factory.FromAsync(
                    socket.BeginSend,
                    socket.EndSend,
                    new[] { new ArraySegment <byte>(new byte[] { 1, 2, 3, 4, 5 }) },
                    SocketFlags.None,
                    null,
                    TaskCreationOptions.None);
                socket.Dispose();
            });

            loop.Run();
            loop.Dispose();
            await t;
        }
Beispiel #6
0
        private async Task ProcessWrites()
        {
            try
            {
                while (true)
                {
                    var buffer = await _output.ReadAsync();

                    try
                    {
                        // Make sure we're on the libuv thread
                        await _thread;

                        if (buffer.IsEmpty && _output.WriterCompleted.IsCompleted)
                        {
                            break;
                        }

                        if (!buffer.IsEmpty)
                        {
                            var writeReq = _thread.WriteReqPool.Allocate();
                            writeReq.Write(_handle, ref buffer, _writeCallback, this);

                            // Preserve this buffer for disposal after the write completes
                            _outgoing.Enqueue(buffer.Preserve());
                        }
                    }
                    finally
                    {
                        buffer.Consumed();
                    }
                }
            }
            catch (Exception ex)
            {
                _output.CompleteReading(ex);
            }
            finally
            {
                _output.CompleteReading();

                // Drain the pending writes
                if (_outgoing.Count > 0)
                {
                    _drainWrites = new TaskCompletionSource <object>();

                    await _drainWrites.Task;
                }

                _handle.Dispose();

                // We'll never call the callback after disposing the handle
                _input.CompleteWriting();
            }
        }
Beispiel #7
0
        private async Task ProcessWrites()
        {
            try
            {
                while (true)
                {
                    var result = await _output.ReadAsync();

                    var buffer = result.Buffer;

                    try
                    {
                        // Make sure we're on the libuv thread
                        await _thread;

                        if (buffer.IsEmpty && result.IsCompleted)
                        {
                            break;
                        }

                        if (!buffer.IsEmpty)
                        {
                            BeginWrite(buffer);
                        }
                    }
                    finally
                    {
                        _output.Advance(buffer.End);
                    }
                }
            }
            catch (Exception ex)
            {
                _output.CompleteReader(ex);
            }
            finally
            {
                _output.CompleteReader();

                // Drain the pending writes
                if (_pendingWrites > 0)
                {
                    _drainWrites = new TaskCompletionSource <object>();

                    await _drainWrites.Task;
                }

                _handle.Dispose();

                // We'll never call the callback after disposing the handle
                _input.CompleteWriter();
            }
        }
        public async Task SocketCanRead()
        {
            var loop = new UvLoopHandle(_logger);

            loop.Init(_uv);
            var tcp = new UvTcpHandle(_logger);

            tcp.Init(loop, (a, b) => { });
            var address = ServerAddress.FromUrl($"http://127.0.0.1:0/");

            tcp.Bind(address);
            var port = tcp.GetSockIPEndPoint().Port;

            tcp.Listen(10, (_, status, error, state) =>
            {
                var tcp2 = new UvTcpHandle(_logger);
                tcp2.Init(loop, (a, b) => { });
                tcp.Accept(tcp2);
                var data = Marshal.AllocCoTaskMem(500);
                tcp2.ReadStart(
                    (a, b, c) => _uv.buf_init(data, 500),
                    (__, nread, state2) =>
                {
                    if (nread <= 0)
                    {
                        tcp2.Dispose();
                    }
                },
                    null);
                tcp.Dispose();
            }, null);
            var t = Task.Run(async() =>
            {
                var socket = TestConnection.CreateConnectedLoopbackSocket(port);
#if NET451
                await Task.Factory.FromAsync(
                    socket.BeginSend,
                    socket.EndSend,
                    new[] { new ArraySegment <byte>(new byte[] { 1, 2, 3, 4, 5 }) },
                    SocketFlags.None,
                    null,
                    TaskCreationOptions.None);
#else
                await socket.SendAsync(new[] { new ArraySegment <byte>(new byte[] { 1, 2, 3, 4, 5 }) },
                                       SocketFlags.None);
#endif
                socket.Dispose();
            });

            loop.Run();
            loop.Dispose();
            await t;
        }
        public async Task SocketCanBeInitAndClose()
        {
            var loop = new UvLoopHandle();

            loop.Init(_uv);
            var tcp = new UvTcpHandle();

            tcp.Init(loop);
            tcp.Bind(new IPEndPoint(IPAddress.Loopback, 0));
            tcp.Dispose();
            loop.Run();
            loop.Dispose();
        }
        public void SocketCanBeInitAndClose()
        {
            var loop = new UvLoopHandle(_logger);

            loop.Init(_uv);
            var tcp = new UvTcpHandle(_logger);

            tcp.Init(loop);
            tcp.Bind("localhost", 0);
            tcp.Dispose();
            loop.Run();
            loop.Dispose();
        }
Beispiel #11
0
        /// <summary>
        /// Creates a connection for a remote endpoint.
        /// </summary>
        /// <param name="context">The listener context to use.</param>
        /// <param name="remote">The endpoint to connect to.</param>
        public static Task <Connection> ConnectAsync(ListenerContext context, IPEndPoint remote)
        {
            var tcs = new TaskCompletionSource <Connection>();

            context.Thread.PostAsync((state) =>
            {
                var socket = new UvTcpHandle();
                try
                {
                    socket.Init(context.Thread.Loop, context.Thread.QueueCloseHandle);
                    socket.NoDelay(true);
                    socket.Connect(context.Thread.Loop, ServiceAddress.FromIPEndPoint(remote), (request, status, ex, sender) =>
                    {
                        request.Dispose();

                        if (ex != null)
                        {
                            // Error has occured, set the exception
                            socket.Dispose();
                            tcs.SetException(ex);
                            return;
                        }

                        // Create the connection and notify
                        var connection = new Connection(context, socket);
                        tcs.SetResult(connection.Start() ? connection : null);
                    }, tcs);
                }
                catch (UvException ex)
                {
                    //Service.Logger.Log(ex);
                    socket.Dispose();
                    tcs.SetException(ex);
                }
            }, tcs);
            return(tcs.Task);
        }
Beispiel #12
0
        private async Task ProcessWrites()
        {
            var writeReq = new UvWriteReq();

            writeReq.Init(_thread.Loop);

            try
            {
                while (true)
                {
                    var buffer = await _output;

                    // Make sure we're on the libuv thread
                    await _thread;

                    if (buffer.IsEmpty && _output.Completion.IsCompleted)
                    {
                        break;
                    }

                    // Up the reference count of the buffer so that we own the disposal of it
                    var cloned = buffer.Clone();
                    _outgoing.Enqueue(cloned);
                    writeReq.Write(_handle, ref cloned, _writeCallback, this);

                    buffer.Consumed();
                }
            }
            catch (Exception ex)
            {
                _output.CompleteReading(ex);
            }
            finally
            {
                _output.CompleteReading();

                // There's pending writes happening
                if (_outgoing.Count > 0)
                {
                    _connectionCompleted = new TaskCompletionSource <object>();

                    await _connectionCompleted.Task;
                }

                writeReq.Dispose();

                _handle.Dispose();
            }
        }
        public void SocketCanBeInitAndClose()
        {
            var loop = new UvLoopHandle(_logger);

            loop.Init(_uv);
            var tcp = new UvTcpHandle(_logger);

            tcp.Init(loop, (a, b) => { });
            var address = ServerAddress.FromUrl("http://127.0.0.1:0/");

            tcp.Bind(address);
            tcp.Dispose();
            loop.Run();
            loop.Dispose();
        }
Beispiel #14
0
        public void SocketCanBeInitAndClose()
        {
            var loop = new UvLoopHandle(_logger);

            loop.Init(_uv);
            var tcp = new UvTcpHandle(_logger);

            tcp.Init(loop, (a, b) => { });
            var endPoint = new IPEndPoint(IPAddress.Loopback, 0);

            tcp.Bind(endPoint);
            tcp.Dispose();
            loop.Run();
            loop.Dispose();
        }
Beispiel #15
0
        private async Task ProcessWrites(UvLoopHandle loop, UvTcpHandle handle)
        {
            var writeReq = new UvWriteReq();

            writeReq.Init(loop);

            try
            {
                while (true)
                {
                    await _output;

                    var buffer = _output.BeginRead();

                    if (buffer.IsEmpty && _output.Completion.IsCompleted)
                    {
                        break;
                    }

                    // Up the reference count of the buffer so that we own the disposal of it
                    var cloned = buffer.Clone();
                    _outgoing.Enqueue(cloned);
                    writeReq.Write(handle, ref cloned, _writeCallback, this);

                    _output.EndRead(buffer);
                }
            }
            catch (Exception ex)
            {
                _output.CompleteReading(ex);
            }
            finally
            {
                _output.CompleteReading();

                // There's pending writes happening
                if (_outgoing.Count > 0)
                {
                    _connectionCompleted = new TaskCompletionSource <object>();

                    await _connectionCompleted.Task;
                }

                writeReq.Dispose();

                handle.Dispose();
            }
        }
Beispiel #16
0
        /// <summary>
        /// Handle an incoming connection
        /// </summary>
        /// <param name="listenSocket">Socket being used to listen on</param>
        /// <param name="status">Connection status</param>
        protected override void OnConnection(UvStreamHandle listenSocket, int status)
        {
            var acceptSocket = new UvTcpHandle(Log);

            try
            {
                acceptSocket.Init(Thread.Loop, Thread.QueueCloseHandle);
                acceptSocket.NoDelay(ServerOptions.NoDelay);
                listenSocket.Accept(acceptSocket);
                DispatchConnection(acceptSocket);
            }
            catch (UvException ex)
            {
                Log.LogError(0, ex, "TcpListener.OnConnection");
                acceptSocket.Dispose();
            }
        }
        private UvTcpHandle AcceptTcp()
        {
            var socket = new UvTcpHandle(TransportContext.Log);

            try
            {
                socket.Init(Thread.Loop, Thread.QueueCloseHandle);
                socket.NoDelay(EndPointInformation.NoDelay);
            }
            catch
            {
                socket.Dispose();
                throw;
            }

            return(socket);
        }
Beispiel #18
0
        private UvTcpHandle AcceptTcp()
        {
            var socket = new UvTcpHandle(TransportContext.Log);

            try
            {
                socket.Init(Thread.Loop, Thread.QueueCloseHandle);
#pragma warning disable CS0618
                socket.NoDelay(TransportContext.Options.NoDelay);
#pragma warning restore CS0618
            }
            catch
            {
                socket.Dispose();
                throw;
            }

            return(socket);
        }
Beispiel #19
0
        public async Task SocketCanRead()
        {
            var loop = new UvLoopHandle(_logger);

            loop.Init(_uv);
            var tcp = new UvTcpHandle(_logger);

            tcp.Init(loop, (a, b) => { });
            var endPoint = new IPEndPoint(IPAddress.Loopback, 0);

            tcp.Bind(endPoint);
            var port = tcp.GetSockIPEndPoint().Port;

            tcp.Listen(10, (_, status, error, state) =>
            {
                var tcp2 = new UvTcpHandle(_logger);
                tcp2.Init(loop, (a, b) => { });
                tcp.Accept(tcp2);
                var data = Marshal.AllocCoTaskMem(500);
                tcp2.ReadStart(
                    (a, b, c) => _uv.buf_init(data, 500),
                    (__, nread, state2) =>
                {
                    if (nread <= 0)
                    {
                        tcp2.Dispose();
                    }
                },
                    null);
                tcp.Dispose();
            }, null);
            var t = Task.Run(async() =>
            {
                var socket = TestConnection.CreateConnectedLoopbackSocket(port);
                await socket.SendAsync(new[] { new ArraySegment <byte>(new byte[] { 1, 2, 3, 4, 5 }) },
                                       SocketFlags.None);
                socket.Dispose();
            });

            loop.Run();
            loop.Dispose();
            await t;
        }
Beispiel #20
0
        /// <summary>
        /// Handle an incoming connection
        /// </summary>
        /// <param name="listenSocket">Socket being used to listen on</param>
        /// <param name="status">Connection status</param>
        protected override void OnConnection(UvStreamHandle listenSocket, int status)
        {
            var acceptSocket = new UvTcpHandle();

            try
            {
                acceptSocket.Init(Thread.Loop, Thread.QueueCloseHandle);
                acceptSocket.NoDelay(true);
                acceptSocket.KeepAlive(true);
                listenSocket.Accept(acceptSocket);
                DispatchConnection(acceptSocket);
            }
            catch (UvException)
            {
                //Service.Logger.Log(ex);
                acceptSocket.Dispose();
                return;
            }
        }
Beispiel #21
0
        private static void OnConnectionCallback(UvStreamHandle listenSocket, int status, Exception error, object state)
        {
            var listener = (UvTcpListener)state;

            var acceptSocket = new UvTcpHandle();

            try
            {
                acceptSocket.Init(listener._thread.Loop, null);
                acceptSocket.NoDelay(true);
                listenSocket.Accept(acceptSocket);
                var connection = new UvTcpConnection(listener._thread, acceptSocket);
                ExecuteCallback(listener, connection);
            }
            catch (UvException)
            {
                acceptSocket.Dispose();
            }
        }
Beispiel #22
0
        private static void OnConnectionCallback(UvStreamHandle listenSocket, int status, Exception error, object state)
        {
            var listener = (UvTcpListener)state;

            var acceptSocket = new UvTcpHandle();

            try
            {
                acceptSocket.Init(listener._thread.Loop, null);
                acceptSocket.NoDelay(true);
                listenSocket.Accept(acceptSocket);
                var connection = new UvTcpConnection(listener._thread, acceptSocket);
                ExecuteCallback(listener, connection);
            }
            catch (UvException)
            {
                acceptSocket.Dispose();
            }
        }
Beispiel #23
0
        private static void OnConnectionCallback(UvStreamHandle listenSocket, int status, Exception error, object state)
        {
            var listener = (UvTcpListener)state;

            var acceptSocket = new UvTcpHandle();

            try
            {
                acceptSocket.Init(listener._thread.Loop, UvThread._queueCloseCallback);
                acceptSocket.NoDelay(true);
                listenSocket.Accept(acceptSocket);
                var connection = new UvTcpServerConnection(listener._thread, acceptSocket);
                listener._callback?.Invoke(connection);
            }
            catch (UvException)
            {
                acceptSocket.Dispose();
            }
        }
Beispiel #24
0
        private async Task ProcessWrites()
        {
            try
            {
                while (!_stopping)
                {
                    var result = await _output.Reader.ReadAsync();

                    var buffer = result.Buffer;

                    try
                    {
                        if (buffer.IsEmpty && result.IsCompleted)
                        {
                            break;
                        }

                        if (!buffer.IsEmpty)
                        {
                            await WriteAsync(buffer);
                        }
                    }
                    finally
                    {
                        _output.Reader.AdvanceTo(buffer.End);
                    }
                }
            }
            catch (Exception ex)
            {
                _output.Reader.Complete(ex);
            }
            finally
            {
                _output.Reader.Complete();

                _handle.Dispose();

                // We'll never call the callback after disposing the handle
                _input.Writer.Complete();
            }
        }
        public async Task SocketCanListenAndAccept()
        {
            var loop = new UvLoopHandle(_logger);

            loop.Init(_uv);
            var tcp = new UvTcpHandle(_logger);

            tcp.Init(loop);
            var address = ServerAddress.FromUrl("http://localhost:54321/");

            tcp.Bind(address);
            tcp.Listen(10, (stream, status, error, state) =>
            {
                var tcp2 = new UvTcpHandle(_logger);
                tcp2.Init(loop);
                stream.Accept(tcp2);
                tcp2.Dispose();
                stream.Dispose();
            }, null);
            var t = Task.Run(async() =>
            {
                var socket = new Socket(
                    AddressFamily.InterNetwork,
                    SocketType.Stream,
                    ProtocolType.Tcp);
#if DNX451
                await Task.Factory.FromAsync(
                    socket.BeginConnect,
                    socket.EndConnect,
                    new IPEndPoint(IPAddress.Loopback, 54321),
                    null,
                    TaskCreationOptions.None);
#else
                await socket.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 54321));
#endif
                socket.Dispose();
            });

            loop.Run();
            loop.Dispose();
            await t;
        }
Beispiel #26
0
        private static void OnConnectionCallback(UvStreamHandle listenSocket, int status, Exception error, object state)
        {
            var listener = (UvTcpListener)state;

            var acceptSocket = new UvTcpHandle(listener.Log);

            try
            {
                acceptSocket.Init(listener.Loop, _queueCloseCallback);
                acceptSocket.NoDelay(true);
                listenSocket.Accept(acceptSocket);
                var connection = new UvTcpConnection(listener, acceptSocket);
                listener._callback?.Invoke(connection);
            }
            catch (UvException ex)
            {
                listener.Log.LogError(0, ex, "UvTcpListener.OnConnection");
                acceptSocket.Dispose();
            }
        }
Beispiel #27
0
        /// <summary>
        /// Creates the socket used to listen for incoming connections
        /// </summary>
        protected override UvStreamHandle CreateListenSocket()
        {
            var socket = new UvTcpHandle(Log);

            try
            {
                socket.Init(Thread.Loop, Thread.QueueCloseHandle);
                socket.NoDelay(ServerOptions.NoDelay);
                socket.Bind(ServerAddress);

                // If requested port was "0", replace with assigned dynamic port.
                ServerAddress.Port = socket.GetSockIPEndPoint().Port;
            }
            catch
            {
                socket.Dispose();
                throw;
            }

            return(socket);
        }
Beispiel #28
0
        public void ServerPipeDispatchConnections()
        {
            var pipeName = @"\\.\pipe\ServerPipeDispatchConnections" + Guid.NewGuid().ToString("n");

            var loop = new UvLoopHandle(_logger);

            loop.Init(_uv);

            var serverConnectionPipe = default(UvPipeHandle);
            var serverConnectionPipeAcceptedEvent = new ManualResetEvent(false);
            var serverConnectionTcpDisposedEvent  = new ManualResetEvent(false);

            var serverListenPipe = new UvPipeHandle(_logger);

            serverListenPipe.Init(loop, (a, b) => { }, false);
            serverListenPipe.Bind(pipeName);
            serverListenPipe.Listen(128, (handle, status, error, state) =>
            {
                serverConnectionPipe = new UvPipeHandle(_logger);
                serverConnectionPipe.Init(loop, (a, b) => { }, true);

                try
                {
                    serverListenPipe.Accept(serverConnectionPipe);
                    serverConnectionPipeAcceptedEvent.Set();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    serverConnectionPipe.Dispose();
                    serverConnectionPipe = null;
                }
            }, null);

            var serverListenTcp = new UvTcpHandle(_logger);

            serverListenTcp.Init(loop, (a, b) => { });
            var address = ServerAddress.FromUrl($"http://127.0.0.1:0/");

            serverListenTcp.Bind(address);
            var port = serverListenTcp.GetSockIPEndPoint().Port;

            serverListenTcp.Listen(128, (handle, status, error, state) =>
            {
                var serverConnectionTcp = new UvTcpHandle(_logger);
                serverConnectionTcp.Init(loop, (a, b) => { });
                serverListenTcp.Accept(serverConnectionTcp);

                serverConnectionPipeAcceptedEvent.WaitOne();

                var writeRequest = new UvWriteReq(new KestrelTrace(new TestKestrelTrace()));
                writeRequest.Init(loop);
                writeRequest.Write2(
                    serverConnectionPipe,
                    new ArraySegment <ArraySegment <byte> >(new ArraySegment <byte>[] { new ArraySegment <byte>(new byte[] { 1, 2, 3, 4 }) }),
                    serverConnectionTcp,
                    (handle2, status2, error2, state2) =>
                {
                    writeRequest.Dispose();
                    serverConnectionTcp.Dispose();
                    serverConnectionTcpDisposedEvent.Set();
                    serverConnectionPipe.Dispose();
                    serverListenPipe.Dispose();
                    serverListenTcp.Dispose();
                },
                    null);
            }, null);

            var worker = new Thread(() =>
            {
                var loop2 = new UvLoopHandle(_logger);
                var clientConnectionPipe = new UvPipeHandle(_logger);
                var connect = new UvConnectRequest(new KestrelTrace(new TestKestrelTrace()));

                loop2.Init(_uv);
                clientConnectionPipe.Init(loop2, (a, b) => { }, true);
                connect.Init(loop2);
                connect.Connect(clientConnectionPipe, pipeName, (handle, status, error, state) =>
                {
                    connect.Dispose();

                    var buf = loop2.Libuv.buf_init(Marshal.AllocHGlobal(64), 64);

                    serverConnectionTcpDisposedEvent.WaitOne();

                    clientConnectionPipe.ReadStart(
                        (handle2, cb, state2) => buf,
                        (handle2, status2, state2) =>
                    {
                        if (status2 == Constants.EOF)
                        {
                            clientConnectionPipe.Dispose();
                            return;
                        }

                        var clientConnectionTcp = new UvTcpHandle(_logger);
                        clientConnectionTcp.Init(loop2, (a, b) => { });
                        clientConnectionPipe.Accept(clientConnectionTcp);
                        var buf2 = loop2.Libuv.buf_init(Marshal.AllocHGlobal(64), 64);
                        clientConnectionTcp.ReadStart(
                            (handle3, cb, state3) => buf2,
                            (handle3, status3, state3) =>
                        {
                            if (status3 == Constants.EOF)
                            {
                                clientConnectionTcp.Dispose();
                            }
                        },
                            null);
                    },
                        null);
                }, null);
                loop2.Run();
                loop2.Dispose();
            });

            var worker2 = new Thread(() =>
            {
                try
                {
                    serverConnectionPipeAcceptedEvent.WaitOne();

                    var socket = TestConnection.CreateConnectedLoopbackSocket(port);
                    socket.Send(new byte[] { 6, 7, 8, 9 });
                    socket.Shutdown(SocketShutdown.Send);
                    var cb = socket.Receive(new byte[64]);
                    socket.Dispose();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            });

            worker.Start();
            worker2.Start();

            loop.Run();
            loop.Dispose();
            worker.Join();
            worker2.Join();
        }
Beispiel #29
0
        public async Task SocketCanReadAndWrite()
        {
            var loop = new UvLoopHandle(_logger);

            loop.Init(_uv);
            var tcp = new UvTcpHandle(_logger);

            tcp.Init(loop, (a, b) => { });
            var endPoint = new IPEndPoint(IPAddress.Loopback, 0);

            tcp.Bind(endPoint);
            var port = tcp.GetSockIPEndPoint().Port;

            tcp.Listen(10, (_, status, error, state) =>
            {
                var tcp2 = new UvTcpHandle(_logger);
                tcp2.Init(loop, (a, b) => { });
                tcp.Accept(tcp2);
                var data = Marshal.AllocCoTaskMem(500);
                tcp2.ReadStart(
                    (a, b, c) => tcp2.Libuv.buf_init(data, 500),
                    async(__, nread, state2) =>
                {
                    if (nread <= 0)
                    {
                        tcp2.Dispose();
                    }
                    else
                    {
                        for (var x = 0; x < 2; x++)
                        {
                            var req = new UvWriteReq(_logger);
                            req.DangerousInit(loop);
                            var block = new ReadOnlyBuffer <byte>(new byte[] { 65, 66, 67, 68, 69 });

                            await req.WriteAsync(
                                tcp2,
                                block);
                        }
                    }
                },
                    null);
                tcp.Dispose();
            }, null);
            var t = Task.Run(async() =>
            {
                var socket = TestConnection.CreateConnectedLoopbackSocket(port);
                await socket.SendAsync(new[] { new ArraySegment <byte>(new byte[] { 1, 2, 3, 4, 5 }) },
                                       SocketFlags.None);
                socket.Shutdown(SocketShutdown.Send);
                var buffer = new ArraySegment <byte>(new byte[2048]);
                while (true)
                {
                    var count = await socket.ReceiveAsync(new[] { buffer }, SocketFlags.None);
                    if (count <= 0)
                    {
                        break;
                    }
                }
                socket.Dispose();
            });

            loop.Run();
            loop.Dispose();
            await t;
        }
Beispiel #30
0
 private void Dispose()
 {
     _listenSocket.Dispose();
 }
        public async Task SocketCanReadAndWrite()
        {
            var loop = new UvLoopHandle(_logger);

            loop.Init(_uv);
            var tcp = new UvTcpHandle(_logger);

            tcp.Init(loop, (a, b) => { });
            var address = ServerAddress.FromUrl($"http://127.0.0.1:0/");

            tcp.Bind(address);
            var port = tcp.GetSockIPEndPoint().Port;

            tcp.Listen(10, (_, status, error, state) =>
            {
                var tcp2 = new UvTcpHandle(_logger);
                tcp2.Init(loop, (a, b) => { });
                tcp.Accept(tcp2);
                var data = Marshal.AllocCoTaskMem(500);
                tcp2.ReadStart(
                    (a, b, c) => tcp2.Libuv.buf_init(data, 500),
                    (__, nread, state2) =>
                {
                    if (nread <= 0)
                    {
                        tcp2.Dispose();
                    }
                    else
                    {
                        for (var x = 0; x < 2; x++)
                        {
                            var req = new UvWriteReq(new KestrelTrace(new TestKestrelTrace()));
                            req.Init(loop); var pool = new MemoryPool();
                            var block = pool.Lease();
                            block.GetIterator().CopyFrom(new ArraySegment <byte>(new byte[] { 65, 66, 67, 68, 69 }));

                            var start = new MemoryPoolIterator(block, 0);
                            var end   = new MemoryPoolIterator(block, block.Data.Count);
                            req.Write(
                                tcp2,
                                start,
                                end,
                                1,
                                (_1, _2, _3, _4) =>
                            {
                                pool.Return(block);
                                pool.Dispose();
                            },
                                null);
                        }
                    }
                },
                    null);
                tcp.Dispose();
            }, null);
            var t = Task.Run(async() =>
            {
                var socket = TestConnection.CreateConnectedLoopbackSocket(port);
#if NET451
                await Task.Factory.FromAsync(
                    socket.BeginSend,
                    socket.EndSend,
                    new[] { new ArraySegment <byte>(new byte[] { 1, 2, 3, 4, 5 }) },
                    SocketFlags.None,
                    null,
                    TaskCreationOptions.None);
#else
                await socket.SendAsync(new[] { new ArraySegment <byte>(new byte[] { 1, 2, 3, 4, 5 }) },
                                       SocketFlags.None);
#endif
                socket.Shutdown(SocketShutdown.Send);
                var buffer = new ArraySegment <byte>(new byte[2048]);
                while (true)
                {
#if NET451
                    var count = await Task.Factory.FromAsync(
                        socket.BeginReceive,
                        socket.EndReceive,
                        new[] { buffer },
                        SocketFlags.None,
                        null,
                        TaskCreationOptions.None);
#else
                    var count = await socket.ReceiveAsync(new[] { buffer }, SocketFlags.None);
#endif
                    if (count <= 0)
                    {
                        break;
                    }
                }
                socket.Dispose();
            });

            loop.Run();
            loop.Dispose();
            await t;
        }