Inheritance: UvStreamHandle
Esempio n. 1
0
        public void Dispose()
        {
            // Ensure the event loop is still running.
            // If the event loop isn't running and we try to wait on this Post
            // to complete, then KestrelEngine will never be disposed and
            // the exception that stopped the event loop will never be surfaced.
            if (Thread.FatalError == null)
            {
                var tcs = new TaskCompletionSource<int>();
                Thread.Post(
                    _ =>
                    {
                        try
                        {
                            ListenSocket.Dispose();
                            tcs.SetResult(0);
                        }
                        catch (Exception ex)
                        {
                            tcs.SetException(ex);
                        }
                    },
                    null);

                // REVIEW: Should we add a timeout here to be safe?
                tcs.Task.Wait();
            }

            ListenSocket = null;
        }
Esempio n. 2
0
        public Task StartAsync(
            string scheme,
            string host,
            int port,
            KestrelThread thread,
            Func<Frame, Task> application)
        {
            Thread = thread;
            Application = application;

            var tcs = new TaskCompletionSource<int>();
            Thread.Post(_ =>
            {
                try
                {
                    ListenSocket = new UvTcpHandle();
                    ListenSocket.Init(Thread.Loop, Thread.QueueCloseHandle);
                    ListenSocket.Bind(new IPEndPoint(IPAddress.Any, port));
                    ListenSocket.Listen(10, _connectionCallback, this);
                    tcs.SetResult(0);
                }
                catch (Exception ex)
                {
                    tcs.SetException(ex);
                }
            }, null);
            return tcs.Task;
        }
 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);
         await Task.Factory.FromAsync(
             socket.BeginConnect,
             socket.EndConnect,
             new IPEndPoint(IPAddress.Loopback, 54321),
             null,
             TaskCreationOptions.None);
         socket.Dispose();
     });
     loop.Run();
     loop.Dispose();
     await t;
 }
 /// <summary>
 /// Creates a socket which can be used to accept an incoming connection
 /// </summary>
 protected override UvStreamHandle CreateAcceptSocket()
 {
     var acceptSocket = new UvTcpHandle(Log);
     acceptSocket.Init(Thread.Loop, Thread.QueueCloseHandle);
     acceptSocket.NoDelay(NoDelay);
     return acceptSocket;
 }
 /// <summary>
 /// Creates the socket used to listen for incoming connections
 /// </summary>
 protected override UvStreamHandle CreateListenSocket(string host, int port)
 {
     var socket = new UvTcpHandle(Log);
     socket.Init(Thread.Loop, Thread.QueueCloseHandle);
     socket.Bind(host, port);
     socket.Listen(Constants.ListenBacklog, ConnectionCallback, this);
     return socket;
 }
 /// <summary>
 /// Creates the socket used to listen for incoming connections
 /// </summary>
 protected override UvStreamHandle CreateListenSocket()
 {
     var socket = new UvTcpHandle(Log);
     socket.Init(Thread.Loop, Thread.QueueCloseHandle);
     socket.NoDelay(NoDelay);
     socket.Bind(ServerAddress);
     socket.Listen(Constants.ListenBacklog, ConnectionCallback, this);
     return socket;
 }
 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();
 }
 public void SocketCanBeInitAndClose()
 {
     var loop = new UvLoopHandle(_logger);
     loop.Init(_uv);
     var tcp = new UvTcpHandle(_logger);
     tcp.Init(loop);
     var address = ServerAddress.FromUrl("http://localhost:0/");
     tcp.Bind(address);
     tcp.Dispose();
     loop.Run();
     loop.Dispose();
 }
        /// <summary>
        /// Handles 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);
            acceptSocket.Init(Thread.Loop, Thread.QueueCloseHandle);

            try
            {
                listenSocket.Accept(acceptSocket);
            }
            catch (UvException ex)
            {
                Log.LogError("TcpListenerPrimary.OnConnection", ex);
                return;
            }

            DispatchConnection(acceptSocket);
        }
Esempio n. 11
0
 public void Dispose()
 {
     var tcs = new TaskCompletionSource<int>();
     Thread.Post(
         _ =>
         {
             try
             {
                 ListenSocket.Dispose();
                 tcs.SetResult(0);
             }
             catch (Exception ex)
             {
                 tcs.SetException(ex);
             }
         },
         null);
     tcs.Task.Wait();
     ListenSocket = null;
 }
Esempio n. 12
0
 protected override void DispatchConnection(UvTcpHandle socket)
 {
     var index = _dispatchIndex++ % (_dispatchPipes.Count + 1);
     if (index == _dispatchPipes.Count)
     {
         base.DispatchConnection(socket);
     }
     else
     {
         var dispatchPipe = _dispatchPipes[index];
         var write = new UvWriteReq();
         write.Init(Thread.Loop);
         write.Write2(
             dispatchPipe,
             _1234,
             socket,
             (write2, status, error, state) => 
             {
                 write2.Dispose();
                 ((UvTcpHandle)state).Dispose();
             },
             socket);
     }
 }
Esempio n. 13
0
 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;
 }
Esempio n. 14
0
 public void tcp_init(UvLoopHandle loop, UvTcpHandle handle)
 {
     loop.Validate();
     handle.Validate();
     Check(_uv_tcp_init(loop, handle));
 }
Esempio n. 15
0
 public static extern int uv_tcp_getpeername(UvTcpHandle handle,out SockAddr name,ref int namelen);
Esempio n. 16
0
 public static extern int uv_tcp_open(UvTcpHandle handle,IntPtr hSocket);
Esempio n. 17
0
 public static extern int uv_tcp_init(UvLoopHandle loop,UvTcpHandle handle);
Esempio n. 18
0
 public void tcp_nodelay(UvTcpHandle handle, bool enable)
 {
     handle.Validate();
     Check(_uv_tcp_nodelay(handle, enable ? 1 : 0));
 }
Esempio n. 19
0
 public void tcp_open(UvTcpHandle handle, IntPtr hSocket)
 {
     handle.Validate();
     Check(_uv_tcp_open(handle, hSocket));
 }
Esempio n. 20
0
        private void OnConnection(UvStreamHandle listenSocket, int status)
        {
            var acceptSocket = new UvTcpHandle();
            acceptSocket.Init(Thread.Loop, Thread.QueueCloseHandle);
            listenSocket.Accept(acceptSocket);

            var connection = new Connection(this, acceptSocket);
            connection.Start();
        }
Esempio n. 21
0
 public static extern int uv_tcp_getpeername(UvTcpHandle handle, out SockAddr name, ref int namelen);
Esempio n. 22
0
 public static extern int uv_tcp_init(UvLoopHandle loop, UvTcpHandle handle);
Esempio n. 23
0
 public void tcp_getpeername(UvTcpHandle handle, out SockAddr addr, ref int namelen)
 {
     handle.Validate();
     Check(_uv_tcp_getpeername(handle, out addr, ref namelen));
 }
Esempio n. 24
0
 public static extern int uv_tcp_bind(UvTcpHandle handle, ref sockaddr addr, int flags);
Esempio n. 25
0
 public static extern int uv_tcp_bind(UvTcpHandle handle,ref SockAddr addr,int flags);
Esempio n. 26
0
 public static extern int uv_tcp_open(UvTcpHandle handle, IntPtr hSocket);
Esempio n. 27
0
 public static extern int uv_tcp_nodelay(UvTcpHandle handle,int enable);
Esempio n. 28
0
 public static extern int uv_tcp_nodelay(UvTcpHandle handle, int enable);
        public async Task SocketCanReadAndWrite()
        {
            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, (_, status, error, state) =>
            {
                Console.WriteLine("Connected");
                var tcp2 = new UvTcpHandle(_logger);
                tcp2.Init(loop);
                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 block = MemoryPoolBlock2.Create(
                                    new ArraySegment<byte>(new byte[] { 65, 66, 67, 68, 69 }),
                                    dataPtr: IntPtr.Zero,
                                    pool: null,
                                    slab: null);
                                var start = new MemoryPoolIterator2(block, 0);
                                var end = new MemoryPoolIterator2(block, block.Data.Count);
                                req.Write(
                                    tcp2,
                                    start,
                                    end,
                                    1,
                                    (_1, _2, _3, _4) =>
                                    {
                                        block.Unpin();
                                    },
                                    null);
                            }
                        }
                    },
                    null);
                tcp.Dispose();
            }, null);
            Console.WriteLine("Task.Run");
            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);
                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.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 54321));
                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 DNX451
                    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
                    Console.WriteLine("count {0} {1}",
                        count,
                        System.Text.Encoding.ASCII.GetString(buffer.Array, 0, count));
                    if (count <= 0) break;
                }
                socket.Dispose();
            });
            loop.Run();
            loop.Dispose();
            await t;
        }
        public Task StartAsync(
            string pipeName,
            KestrelThread thread,
            Func<Frame, Task> application)
        {
            Thread = thread;
            Application = application;

            DispatchPipe = new UvPipeHandle();

            var tcs = new TaskCompletionSource<int>();
            Thread.Post(_ =>
            {
                try
                {
                    DispatchPipe.Init(Thread.Loop, true);
                    var connect = new UvConnectRequest();
                    connect.Init(Thread.Loop);
                    connect.Connect(
                        DispatchPipe,
                        pipeName,
                        (connect2, status, error, state) =>
                        {
                            connect.Dispose();
                            if (error != null)
                            {
                                tcs.SetException(error);
                                return;
                            }

                            try
                            {
                                var ptr = Marshal.AllocHGlobal(4);
                                var buf = Thread.Loop.Libuv.buf_init(ptr, 4);

                                DispatchPipe.ReadStart(
                                    (_1, _2, _3) => buf,
                                    (_1, status2, error2, state2) =>
                                    {
                                        if (status2 == 0)
                                        {
                                            DispatchPipe.Dispose();
                                            Marshal.FreeHGlobal(ptr);
                                            return;
                                        }

                                        var acceptSocket = new UvTcpHandle();
                                        acceptSocket.Init(Thread.Loop, Thread.QueueCloseHandle);

                                        try
                                        {
                                            DispatchPipe.Accept(acceptSocket);
                                        }
                                        catch (Exception ex)
                                        {
                                            Trace.WriteLine("DispatchPipe.Accept " + ex.Message);
                                            acceptSocket.Dispose();
                                            return;
                                        }

                                        var connection = new Connection(this, acceptSocket);
                                        connection.Start();
                                    },
                                    null);

                                tcs.SetResult(0);
                            }
                            catch (Exception ex)
                            {
                                DispatchPipe.Dispose();
                                tcs.SetException(ex);
                            }
                        },
                        null);
                }
                catch (Exception ex)
                {
                    DispatchPipe.Dispose();
                    tcs.SetException(ex);
                }
            }, null);
            return tcs.Task;
        }
Esempio n. 31
0
 public void tcp_bind(UvTcpHandle handle, ref sockaddr addr, int flags)
 {
     handle.Validate();
     Check(_uv_tcp_bind(handle, ref addr, flags));
 }
Esempio n. 32
0
 public void tcp_bind(UvTcpHandle handle, ref SockAddr addr, int flags)
 {
     handle.Validate();
     Check(_uv_tcp_bind(handle, ref addr, flags));
 }
        public void ServerPipeDispatchConnections()
        {
            var pipeName = @"\\.\pipe\ServerPipeDispatchConnections" + Guid.NewGuid().ToString("n");

            var loop = new UvLoopHandle();
            loop.Init(_uv);

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

            var serverListenPipe = new UvPipeHandle();
            serverListenPipe.Init(loop, false);
            serverListenPipe.Bind(pipeName);
            serverListenPipe.Listen(128, (_1, status, error, _2) =>
            {
                serverConnectionPipe = new UvPipeHandle();
                serverConnectionPipe.Init(loop, true);
                try
                {
                    serverListenPipe.Accept(serverConnectionPipe);
                    serverConnectionPipeAcceptedEvent.Set();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    serverConnectionPipe.Dispose();
                    serverConnectionPipe = null;
                }
            }, null);

            var serverListenTcp = new UvTcpHandle();
            serverListenTcp.Init(loop);
            serverListenTcp.Bind(new IPEndPoint(0, 54321));
            serverListenTcp.Listen(128, (_1, status, error, _2) =>
            {
                var serverConnectionTcp = new UvTcpHandle();
                serverConnectionTcp.Init(loop);
                serverListenTcp.Accept(serverConnectionTcp);

                serverConnectionPipeAcceptedEvent.WaitOne();

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

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

                loop2.Init(_uv);
                clientConnectionPipe.Init(loop2, true);
                connect.Init(loop2);
                connect.Connect(clientConnectionPipe, pipeName, (_1, status, error, _2) =>
                {
                    connect.Dispose();

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

                    serverConnectionTcpDisposedEvent.WaitOne();

                    clientConnectionPipe.ReadStart(
                        (_3, cb, _4) => buf,
                        (_3, status2, error2, _4) =>
                        {
                            if (status2 == 0)
                            {
                                clientConnectionPipe.Dispose();
                                return;
                            }
                            var clientConnectionTcp = new UvTcpHandle();
                            clientConnectionTcp.Init(loop2);
                            clientConnectionPipe.Accept(clientConnectionTcp);
                            var buf2 = loop2.Libuv.buf_init(Marshal.AllocHGlobal(64), 64);
                            clientConnectionTcp.ReadStart(
                                (_5, cb, _6) => buf2,
                                (_5, status3, error3, _6) =>
                                {
                                    if (status3 == 0)
                                    {
                                        clientConnectionTcp.Dispose();
                                    }
                                },
                                null);
                        },
                        null);
                }, null);
                loop2.Run();
                loop2.Dispose();
            });

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

                    var socket = new Socket(SocketType.Stream, ProtocolType.IP);
                    socket.Connect(IPAddress.Loopback, 54321);
                    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();
        }
Esempio n. 34
0
 public void tcp_open(UvTcpHandle handle, IntPtr hSocket)
 {
     handle.Validate();
     Check(_uv_tcp_open(handle, hSocket));
 }
Esempio n. 35
0
 public async Task SocketCanReadAndWrite()
 {
     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) => tcp2.Libuv.buf_init(data, 500),
             (__, nread, error2, state2) =>
             {
                 bytesRead += nread;
                 if (nread == 0)
                 {
                     tcp2.Dispose();
                 }
                 else
                 {
                     for (var x = 0; x != 2; ++x)
                     {
                         var req = new UvWriteReq();
                         req.Init(loop);
                         req.Write(
                             tcp2,
                             new ArraySegment<ArraySegment<byte>>(
                                 new[] { new ArraySegment<byte>(new byte[] { 65, 66, 67, 68, 69 }) }
                                 ),
                             (_1, _2, _3, _4) => { },
                             null);
                     }
                 }
             },
             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.Shutdown(SocketShutdown.Send);
         var buffer = new ArraySegment<byte>(new byte[2048]);
         for (; ;)
         {
             var count = await Task.Factory.FromAsync(
                 socket.BeginReceive,
                 socket.EndReceive,
                 new[] { buffer },
                 SocketFlags.None,
                 null,
                 TaskCreationOptions.None);
             Console.WriteLine("count {0} {1}",
                 count,
                 System.Text.Encoding.ASCII.GetString(buffer.Array, 0, count));
             if (count <= 0) break;
         }
         socket.Dispose();
     });
     loop.Run();
     loop.Dispose();
     await t;
 }
Esempio n. 36
0
 public void tcp_nodelay(UvTcpHandle handle, bool enable)
 {
     handle.Validate();
     Check(_uv_tcp_nodelay(handle, enable ? 1 : 0));
 }
Esempio n. 37
0
 public void tcp_init(UvLoopHandle loop, UvTcpHandle handle)
 {
     loop.Validate();
     handle.Validate();
     Check(_uv_tcp_init(loop, handle));
 }
Esempio n. 38
0
 public void tcp_getpeername(UvTcpHandle handle, out SockAddr addr, ref int namelen)
 {
     handle.Validate();
     Check(_uv_tcp_getpeername(handle, out addr, ref namelen));
 }