示例#1
1
        public void Socket_SendReceive_Success()
        {
            string path = GetRandomNonExistingFilePath();
            var endPoint = new UnixDomainSocketEndPoint(path);
            try
            {
                using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                {
                    server.Bind(endPoint);
                    server.Listen(1);

                    client.Connect(endPoint);
                    using (Socket accepted = server.Accept())
                    {
                        var data = new byte[1];
                        for (int i = 0; i < 10; i++)
                        {
                            data[0] = (byte)i;

                            accepted.Send(data);
                            data[0] = 0;

                            Assert.Equal(1, client.Receive(data));
                            Assert.Equal(i, data[0]);
                        }
                    }
                }
            }
            finally
            {
                try { File.Delete(path); }
                catch { }
            }
        }
示例#2
0
        private static void StartServer(String path)
        {
            var endPoint = new UnixDomainSocketEndPoint(path);

            try
            {
                using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                {
                    server.Bind(endPoint);
                    Console.WriteLine($"[Server] Listening ... ..{path}");
                    server.Listen(1);
                    using (Socket accepted = server.Accept())
                    {
                        Console.WriteLine("[Server]Connection Accepted ..." + accepted.RemoteEndPoint.ToString());
                        var bytes = new byte[100];
                        while (true)
                        {
                            int    byteRecv = accepted.Receive(bytes);
                            String str      = Encoding.UTF8.GetString(bytes, 0, byteRecv);
                            Console.WriteLine("[Server]Received " + str);
                            accepted.Send(Encoding.UTF8.GetBytes(str.ToUpper()));
                        }
                    }
                }
            }
            finally
            {
                try { File.Delete(path); }
                catch { }
            }
        }
示例#3
0
        private static void StartClient(String path)
        {
            var endPoint = new UnixDomainSocketEndPoint(path);

            try
            {
                using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                {
                    client.Connect(endPoint);
                    Console.WriteLine($"[Client] Connected to ... ..{path}");
                    String str   = String.Empty;
                    var    bytes = new byte[100];
                    while (!str.Equals("exit", StringComparison.InvariantCultureIgnoreCase))
                    {
                        Console.WriteLine("[Client]Enter something: ");
                        var line = Console.ReadLine();
                        client.Send(Encoding.UTF8.GetBytes(line));
                        Console.Write("[Client]From Server: ");

                        int byteRecv = client.Receive(bytes);
                        str = Encoding.UTF8.GetString(bytes, 0, byteRecv);
                        Console.WriteLine(str);
                    }
                }
            }
            finally
            {
                try { File.Delete(path); }
                catch { }
            }
        }
示例#4
0
        static async Task RunClientAsync(string path)
        {
            var endpoint = new UnixDomainSocketEndPoint(path);

            using (var client = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Unspecified))
            {
                Console.WriteLine("Client: Connecting to {0}.", endpoint);
                await client.ConnectAsync(endpoint);

                Console.WriteLine("Client: Connected at {0}.", client.RemoteEndPoint);
                using (var ns = new NetworkStream(client))
                    using (var reader = new StreamReader(ns))
                    {
                        ns.WriteByte(PROLOGUE);
                        Console.WriteLine("Client: Sent prologue.");
                        while (true)
                        {
                            var line = await reader.ReadLineAsync();

                            Console.WriteLine("CLIENT >{0}", line);
                            ns.WriteByte(ACKOWLEDGE);
                            if (line == "")
                            {
                                break;
                            }
                        }
                    }

                Console.WriteLine("Client: Shutting down…");
                client.Shutdown(SocketShutdown.Both);
                client.Close();
            }
        }
        public TestServer(TestServerOptions options = null)
        {
            options = options ?? new TestServerOptions();
            _connectionDispatcher = options.ConnectionDispatcher;
            var transportOptions = new LinuxTransportOptions()
            {
                ThreadCount = options.ThreadCount,
                DeferAccept = options.DeferAccept,
                AioReceive  = options.AioReceive,
                AioSend     = options.AioSend,
                ApplicationSchedulingMode = options.ApplicationSchedulingMode,
            };
            var      loggerFactory = new LoggerFactory();
            EndPoint endPoint      = null;

            if (options.UnixSocketPath != null)
            {
                _unixSocketPath = options.UnixSocketPath;
                endPoint        = new UnixDomainSocketEndPoint(_unixSocketPath);
            }
            else
            {
                _serverAddress = options.IPEndPoint ?? new IPEndPoint(IPAddress.Loopback, 0);
                endPoint       = _serverAddress;
            }
            _transport = new Transport(endPoint, transportOptions, loggerFactory);
        }
示例#6
0
        public async Task Socket_ConnectAsyncUnixDomainSocketEndPoint_NotServer()
        {
            string path     = GetRandomNonExistingFilePath();
            var    endPoint = new UnixDomainSocketEndPoint(path);

            try
            {
                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.RemoteEndPoint = endPoint;
                args.Completed     += (s, e) => ((TaskCompletionSource)e.UserToken).SetResult();

                var complete = new TaskCompletionSource();
                args.UserToken = complete;

                using (Socket sock = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                {
                    bool willRaiseEvent = sock.ConnectAsync(args);
                    if (willRaiseEvent)
                    {
                        await complete.Task;
                    }

                    Assert.Equal(
                        RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? SocketError.ConnectionRefused : SocketError.AddressNotAvailable,
                        args.SocketError);
                }
            }
            finally
            {
                try { File.Delete(path); }
                catch { }
            }
        }
示例#7
0
        public OutputSocketManager()
        {
            socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);

            if (File.Exists(serveraddress))
            {
                File.Delete(serveraddress);
            }

            var serverendpoint = new UnixDomainSocketEndPoint(serveraddress);

            socket.Bind(serverendpoint);

            clientthread = new Thread(() =>
            {
                while (true)
                {
                    socket.Listen(1);

                    var clientsocket = socket.Accept();

                    clients.Add(clientsocket);
                }
            });

            clientthread.Start();
        }
示例#8
0
    private static void ConnectAsClient(string[] args)
    {
        try
        {
            var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
            var unixEp = new UnixDomainSocketEndPoint(_socketPath);

            // Under .NET Core 2.1, you can use user-defined UnixEndPoint type
            // var unixEp = new UnixEndPoint(_socketPath);

            System.IO.File.WriteAllLines(_ListPath, args);

            socket.Connect(unixEp);
            Console.WriteLine("[Client] Conencted");

            NetworkStream networkStream = new NetworkStream(socket);
            if (networkStream.CanWrite)
            {
                byte[] WriteBuffer = Encoding.ASCII.GetBytes(args[0]);
                networkStream.Write(WriteBuffer, 0, WriteBuffer.Length);
            }

            socket.Close();
        }
        catch (System.Exception err)
        {
            System.IO.File.WriteAllLines(_ListPath, args);
            System.IO.File.AppendAllLines(_ListPath, new String[] { err.Message, err.StackTrace });
        }

        Console.WriteLine("[Client] Closed");
    }
示例#9
0
        public async Task Unix_Client_Connect_Ping_Disconnect()
        {
            var unixEndPoint = new UnixDomainSocketEndPoint("/var/run/redis/redis.sock");

            using (var client = new RedisClient(unixEndPoint))
                await client.Ping();
        }
示例#10
0
        public ReverseServer(string serverAddress, int bufferSize = 16 * 1024)
        {
            _serverAddress = serverAddress;
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                _server = new NamedPipeServerStream(
                    serverAddress,
                    PipeDirection.InOut,
                    NamedPipeServerStream.MaxAllowedServerInstances,
                    PipeTransmissionMode.Byte,
                    PipeOptions.None,
                    bufferSize,
                    bufferSize);
            }
            else
            {
                if (File.Exists(serverAddress))
                {
                    File.Delete(serverAddress);
                }
                var remoteEP = new UnixDomainSocketEndPoint(serverAddress);

                var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
                // socket(7) states that SO_RCVBUF has a minimum of 128 and SO_SNDBUF has minimum of 1024
                socket.SendBufferSize    = Math.Max(bufferSize, 1024);
                socket.ReceiveBufferSize = Math.Max(bufferSize, 128);
                socket.Bind(remoteEP);
                socket.Listen(255);
                socket.LingerState.Enabled = false;
                _server = socket;
            }
        }
示例#11
0
        private static async System.Threading.Tasks.Task TestUnixgramSendAsync()
        {
            Console.WriteLine("TestUnixgramSendAsync start:");
            string   filepath   = "/tmp/udp.sock";
            EndPoint ipEndPoint = new UnixDomainSocketEndPoint(filepath);
            string   address    = $"unixgram://{filepath}";

            try { File.Delete(filepath); } catch (Exception) { };
            using (Socket socket = new Socket(AddressFamily.Unix, SocketType.Dgram, ProtocolType.Unspecified))
            {
                socket.Bind(ipEndPoint);
                byte[]        bytes        = new byte[1024];
                var           bytesRecTask = socket.ReceiveAsync(bytes, SocketFlags.None);
                MetricMessage msg          = new MetricMessage("mymeasure", "ping", 0.03d);
                string        sample       = msg.ToString();
                var           transport    = TgfClientProvider.GetTransport(address);
                TgfClient     client       = new TgfClient(transport);
                client.SendMetric("mymeasure", "ping", 0.03d);
                transport.Disconnect();
                int    bytesRec = await bytesRecTask;
                string msgRcv   = Encoding.UTF8.GetString(bytes, 0, bytesRec);
                if (!sample.Equals(msgRcv.Trim()))
                {
                    throw new Exception($"TestUnixgramSendAsync: {msgRcv} not equal {sample}");
                }
            }
            try { File.Delete(filepath); } catch (Exception) { };
            Console.WriteLine("TestUnixgramSendAsync end");
        }
示例#12
0
        public ReverseServer(string serverAddress, int bufferSize = 16 * 1024)
        {
            _serverAddress = serverAddress;
            _bufferSize    = bufferSize;
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                _server = GetNewNamedPipeServer();
            }
            else
            {
                if (File.Exists(serverAddress))
                {
                    File.Delete(serverAddress);
                }
                var remoteEP = new UnixDomainSocketEndPoint(serverAddress);

                var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
                // socket(7) states that SO_RCVBUF has a minimum of 128 and SO_SNDBUF has minimum of 1024
                socket.SendBufferSize    = Math.Max(bufferSize, 1024);
                socket.ReceiveBufferSize = Math.Max(bufferSize, 128);
                socket.Bind(remoteEP);
                socket.Listen(255);
                _server = socket;
            }
        }
示例#13
0
        static WaylandWireConnection ConnectToDisplay(string display = null)
        {
            display ??= Environment.GetEnvironmentVariable("WAYLAND_DISPLAY");
            display ??= "wayland-0";

            string path;

            if (display.StartsWith('/'))
            {
                path = display;
            }
            else
            {
                string xdgRuntimeDir = Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR");
                if (xdgRuntimeDir == null)
                {
                    throw new Exception("XDG_RUNTIME_DIR missing from environment");
                }
                path = Path.Join(xdgRuntimeDir, display);
            }

            Socket   socket   = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
            EndPoint endpoint = new UnixDomainSocketEndPoint(path);

            socket.Connect(endpoint);
            return(new WaylandWireConnection(socket));
        }
        /// <summary>
        /// Establishes a connection to the given UNIX socket file
        /// </summary>
        /// <param name="initMessage">Init message to send to the server</param>
        /// <param name="socketPath">Path to the UNIX socket file</param>
        /// <param name="cancellationToken">Optional cancellation token</param>
        /// <returns>Asynchronous task</returns>
        /// <exception cref="IncompatibleVersionException">API level is incompatible</exception>
        /// <exception cref="IOException">Connection mode is unavailable</exception>
        /// <exception cref="OperationCanceledException">Operation has been cancelled</exception>
        /// <exception cref="SocketException">Connection has been closed</exception>
        protected async Task Connect(ClientInitMessage initMessage, string socketPath, CancellationToken cancellationToken)
        {
            // Create a new connection
            UnixDomainSocketEndPoint endPoint = new UnixDomainSocketEndPoint(socketPath);

            _unixSocket.Connect(endPoint);

            // Read the server init message
            ServerInitMessage ownMessage    = new ServerInitMessage();
            ServerInitMessage serverMessage = await Receive <ServerInitMessage>(cancellationToken);

            Id = serverMessage.Id;

            // Switch mode
            initMessage.Version = Defaults.ProtocolVersion;
            await Send(initMessage, cancellationToken);

            // Check the result
            BaseResponse response = await ReceiveResponse(cancellationToken);

            if (!response.Success)
            {
                ErrorResponse errorResponse = (ErrorResponse)response;
                if (errorResponse.ErrorType == nameof(IncompatibleVersionException))
                {
                    throw new IncompatibleVersionException(errorResponse.ErrorMessage);
                }
                throw new IOException($"Could not set connection type {_connectionMode} ({errorResponse.ErrorType}: {errorResponse.ErrorMessage})");
            }
        }
示例#15
0
        public async Task Socket_SendReceiveAsync_Success()
        {
            string path     = GetRandomNonExistingFilePath();
            var    endPoint = new UnixDomainSocketEndPoint(path);

            using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                {
                    server.Bind(endPoint);
                    server.Listen(1);

                    await client.ConnectAsync(endPoint);

                    using (Socket accepted = await server.AcceptAsync())
                    {
                        var data = new byte[1];
                        for (int i = 0; i < 10; i++)
                        {
                            data[0] = (byte)i;

                            await accepted.SendAsync(new ArraySegment <byte>(data), SocketFlags.None);

                            data[0] = 0;

                            Assert.Equal(1, await client.ReceiveAsync(new ArraySegment <byte>(data), SocketFlags.None));
                            Assert.Equal(i, data[0]);
                        }
                    }
                }

            Assert.False(File.Exists(path));
        }
示例#16
0
    static void threadFunc()
    {
        Console.WriteLine("[Server] Thread is started.");

        if (File.Exists(_socketPath) == true)
        {
            File.Delete(_socketPath);
        }

        try
        {
            using (var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP))
            {
                var unixEp = new UnixDomainSocketEndPoint(_socketPath);

                // Under .NET Core 2.1, you can use user-defined UnixEndPoint type
                // var unixEp = new UnixEndPoint(_socketPath);

                socket.Bind(unixEp);
                socket.Listen(5);
                while (true)
                {
                    using (Socket clntSocket = socket.Accept())
                    {
                        Console.WriteLine("[Server] ClientConencted");
                    }
                    Console.WriteLine("[Server] ClientClosed");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
示例#17
0
        /// <summary>
        /// Establishes a connection to the given UNIX socket file
        /// </summary>
        /// <param name="initMessage">Init message to send to the server</param>
        /// <param name="socketPath">Path to the UNIX socket file</param>
        /// <param name="cancellationToken">Optional cancellation token</param>
        /// <returns>Asynchronous task</returns>
        /// <exception cref="IncompatibleVersionException">API level is incompatible</exception>
        /// <exception cref="IOException">Connection mode is unavailable</exception>
        protected async Task Connect(ClientInitMessage initMessage, string socketPath, CancellationToken cancellationToken)
        {
            // Create a new connection
            UnixDomainSocketEndPoint endPoint = new UnixDomainSocketEndPoint(socketPath);

            _unixSocket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
            _unixSocket.Connect(endPoint);

            // Make sure we can deserialize incoming data
            _networkStream = new NetworkStream(_unixSocket);
            _streamReader  = new StreamReader(_networkStream);
            InitReader();

            // Verify server init message
            ServerInitMessage expectedMessage = new ServerInitMessage();
            ServerInitMessage serverMessage   = await Receive <ServerInitMessage>(cancellationToken);

            if (serverMessage.Version < expectedMessage.Version)
            {
                throw new IncompatibleVersionException($"Incompatible API version (expected {expectedMessage.Version}, got {serverMessage.Version}");
            }
            Id = serverMessage.Id;

            // Switch mode
            await Send(initMessage);

            BaseResponse response = await ReceiveResponse <object>(cancellationToken);

            if (!response.Success)
            {
                ErrorResponse errorResponse = (ErrorResponse)response;
                throw new IOException($"Could not set connection type {_connectionMode} ({errorResponse.ErrorType}: {errorResponse.ErrorMessage})");
            }
        }
        /// <summary>
        /// Open a new UNIX socket on the given file path
        /// </summary>
        /// <param name="endpointType">Type of this HTTP endpoint</param>
        /// <param name="ns">Namespace of this HTTP endpoint</param>
        /// <param name="endpointPath">Path of this HTTP endpoint</param>
        /// <param name="socketPath">Path to the UNIX socket file</param>
        /// <param name="backlog">Number of simultaneously pending connections</param>
        /// <exception cref="IOException">Socket could not be opened</exception>
        public HttpEndpointUnixSocket(HttpEndpointType endpointType, string ns, string endpointPath, string socketPath, int backlog = DefaultBacklog)
        {
            // Set up information about this HTTP endpoint
            EndpointType = endpointType;
            Namespace    = ns;
            EndpointPath = endpointPath;
            SocketPath   = socketPath;

            // Clean up socket path again in case of unclean exit
            File.Delete(socketPath);

            // Create a new UNIX socket and start listening
            try
            {
                UnixDomainSocketEndPoint endPoint = new UnixDomainSocketEndPoint(socketPath);
                _unixSocket.Bind(endPoint);
                _unixSocket.Listen(backlog);
                AcceptConnections();
            }
            catch
            {
                _unixSocket.Close();
                throw;
            }
        }
示例#19
0
        public void Socket_SendReceive_Success()
        {
            string path     = GetRandomNonExistingFilePath();
            var    endPoint = new UnixDomainSocketEndPoint(path);

            using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                {
                    server.Bind(endPoint);
                    server.Listen(1);

                    client.Connect(endPoint);
                    using (Socket accepted = server.Accept())
                    {
                        var data = new byte[1];
                        for (int i = 0; i < 10; i++)
                        {
                            data[0] = (byte)i;

                            accepted.Send(data);
                            data[0] = 0;

                            Assert.Equal(1, client.Receive(data));
                            Assert.Equal(i, data[0]);
                        }
                    }
                }

            Assert.False(File.Exists(path));
        }
示例#20
0
        public void Socket_ConnectAsyncUnixDomainSocketEndPoint_NotServer()
        {
            string path     = GetRandomNonExistingFilePath();
            var    endPoint = new UnixDomainSocketEndPoint(path);

            SocketAsyncEventArgs args = new SocketAsyncEventArgs();

            args.RemoteEndPoint = endPoint;
            args.Completed     += OnConnectAsyncCompleted;

            ManualResetEvent complete = new ManualResetEvent(false);

            args.UserToken = complete;

            Socket sock = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);

            bool willRaiseEvent = sock.ConnectAsync(args);

            if (willRaiseEvent)
            {
                complete.WaitOne();
            }

            Assert.Equal(SocketError.SocketError, args.SocketError);

            complete.Dispose();
            sock.Dispose();
        }
示例#21
0
        public static ulong SendCommand(int processId, byte[] buffer)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                var pipeName = $"dotnetcore-diagnostic-{processId}";
                using (var namedPipe = new NamedPipeClientStream(
                           ".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation))
                {
                    namedPipe.Connect((int)ConnectTimeoutMilliseconds);
                    namedPipe.Write(buffer, 0, buffer.Length);

                    return(new BinaryReader(namedPipe).ReadUInt64());
                }
            }
            else
            {
                var ipcPort = Directory.GetFiles(IpcRootPath) // Try best match.
                              .Select(namedPipe => (new FileInfo(namedPipe)).Name)
                              .Single(input => Regex.IsMatch(input, $"^dotnetcore-diagnostic-{processId}-(\\d+)-socket$"));
                var path     = Path.Combine(Path.GetTempPath(), ipcPort);
                var remoteEP = new UnixDomainSocketEndPoint(path);

                using (var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                {
                    socket.Connect(remoteEP);
                    socket.Send(buffer);

                    var content        = new byte[sizeof(ulong)];
                    var nReceivedBytes = socket.Receive(content);
                    return((nReceivedBytes == sizeof(ulong)) ? BitConverter.ToUInt64(content, 0) : 0);
                }
            }
        }
示例#22
0
        /// <summary>
        /// Establishes a connection to the given UNIX socket file
        /// </summary>
        /// <param name="initMessage">Init message to send to the server</param>
        /// <param name="socketPath">Path to the UNIX socket file</param>
        /// <param name="cancellationToken">Optional cancellation token</param>
        /// <returns>Asynchronous task</returns>
        /// <exception cref="IncompatibleVersionException">API level is incompatible</exception>
        /// <exception cref="IOException">Connection mode is unavailable</exception>
        /// <exception cref="OperationCanceledException">Operation has been cancelled</exception>
        /// <exception cref="SocketException">Connection has been closed</exception>
        protected async Task Connect(ClientInitMessage initMessage, string socketPath, CancellationToken cancellationToken)
        {
            // Create a new connection
            UnixDomainSocketEndPoint endPoint = new UnixDomainSocketEndPoint(socketPath);

            _unixSocket.Connect(endPoint);

            // Verify server init message
            ServerInitMessage ownMessage    = new ServerInitMessage();
            ServerInitMessage serverMessage = await Receive <ServerInitMessage>(cancellationToken);

            if (serverMessage.Version < ownMessage.Version)
            {
                throw new IncompatibleVersionException($"Incompatible API version (need {ownMessage.Version}, got {serverMessage.Version}");
            }
            Id = serverMessage.Id;

            // Switch mode
            await Send(initMessage, cancellationToken);

            BaseResponse response = await ReceiveResponse(cancellationToken);

            if (!response.Success)
            {
                ErrorResponse errorResponse = (ErrorResponse)response;
                throw new IOException($"Could not set connection type {_connectionMode} ({errorResponse.ErrorType}: {errorResponse.ErrorMessage})");
            }
        }
示例#23
0
        /// <summary>
        /// Get the OS Transport to be used for communicating with a dotnet process.
        /// </summary>
        /// <param name="processId">The PID of the dotnet process to get the transport for</param>
        /// <returns>A System.IO.Stream wrapper around the transport</returns>
        private static Stream GetTransport(int processId)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                string pipeName  = $"dotnet-diagnostic-{processId}";
                var    namedPipe = new NamedPipeClientStream(
                    ".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation);
                namedPipe.Connect((int)ConnectTimeoutMilliseconds);
                return(namedPipe);
            }
            else
            {
                string ipcPort = Directory.GetFiles(IpcRootPath) // Try best match.
                                 .Select(namedPipe => (new FileInfo(namedPipe)).Name)
                                 .SingleOrDefault(input => Regex.IsMatch(input, $"^dotnet-diagnostic-{processId}-(\\d+)-socket$"));
                if (ipcPort == null)
                {
                    throw new PlatformNotSupportedException($"Process {processId} not running compatible .NET Core runtime");
                }
                string path     = Path.Combine(Path.GetTempPath(), ipcPort);
                var    remoteEP = new UnixDomainSocketEndPoint(path);

                var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
                socket.Connect(remoteEP);
                return(new NetworkStream(socket));
            }
        }
示例#24
0
        public async Task StartAsync <TContext>(IHttpApplication <TContext> application, CancellationToken cancellationToken)
        {
            try
            {
                // Kestrel does not support big-endian architectures. Kestrel
                // 不支持大端模式的处理器
                //https://www.cnblogs.com/little-white/p/3236548.html
                if (!BitConverter.IsLittleEndian)
                {
                    throw new PlatformNotSupportedException(CoreStrings.BigEndianNotSupported);
                }
                EndPoint endPoint;
                if (ServerOptions.Host.StartsWith("unix://", StringComparison.Ordinal))
                {
                    endPoint = new UnixDomainSocketEndPoint(ServerOptions.Host.Substring(ServerOptions.Host.IndexOf("unix://") + 1));
                }
                else if (ServerOptions.Host.Contains("localhost"))
                {
                    endPoint = new IPEndPoint(IPAddress.Loopback, ServerOptions.Port);
                }
                else if (IPAddress.TryParse(ServerOptions.Host, out var ip))
                {
                    endPoint = new IPEndPoint(ip, ServerOptions.Port);
                }
                else
                {
                    endPoint = new IPEndPoint(IPAddress.IPv6Any, ServerOptions.Port);
                }
                async Task OnBind(EndPoint _endPoint)
                {
                    // 构建委托:用于处理socket请求
                    var connectionBuilder = new ConnectionBuilder();

                    connectionBuilder.Use(next => { return(new HttpConnectionMiddleware <TContext>(application).OnConnectionAsync); });
                    var connectionDelegate = connectionBuilder.Build();

                    // Add the connection limit middleware
                    //if (Options.Limits.MaxConcurrentConnections.HasValue)
                    //{
                    //    connectionDelegate = new ConnectionLimitMiddleware(connectionDelegate, Options.Limits.MaxConcurrentConnections.Value, Trace).OnConnectionAsync;
                    //}

                    // 构建服务端Socket: 用于进行监听客户端请求
                    var g         = _transportFactory.BindAsync(_endPoint).Result;
                    var transport = await _transportFactory.BindAsync(_endPoint).ConfigureAwait(false);

                    // 通过 ThreadPool.UnsafeQueueUserWorkItem,分配任务: 服务端接收 socket请求连接,处理请求
                    var connectionDispatcher = new ConnectionDispatcher(connectionDelegate, ServiceContext);
                    var acceptLoopTask       = connectionDispatcher.StartAcceptingConnections(transport);
                }
                await OnBind(endPoint);
            }
            catch (Exception ex)
            {
                Dispose();
                throw;
            }
            throw new NotImplementedException();
        }
示例#25
0
        public async Task Socket_SendReceiveAsync_PropagateToStream_Success(int iterations, int writeBufferSize, int readBufferSize)
        {
            var writeBuffer = new byte[writeBufferSize * iterations];

            Random.Shared.NextBytes(writeBuffer);
            var readData = new MemoryStream();

            string path     = GetRandomNonExistingFilePath();
            var    endPoint = new UnixDomainSocketEndPoint(path);

            try
            {
                using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                    using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                    {
                        server.Bind(endPoint);
                        server.Listen(1);

                        Task <Socket> serverAccept = server.AcceptAsync();
                        await Task.WhenAll(serverAccept, client.ConnectAsync(endPoint));

                        Task clientReceives = Task.Run(async() =>
                        {
                            byte[] buffer = new byte[readBufferSize];
                            while (true)
                            {
                                int bytesRead = await client.ReceiveAsync(new Memory <byte>(buffer), SocketFlags.None);
                                if (bytesRead == 0)
                                {
                                    break;
                                }
                                Assert.InRange(bytesRead, 1, writeBuffer.Length - readData.Length);
                                readData.Write(buffer, 0, bytesRead);
                            }
                        });

                        using (Socket accepted = await serverAccept)
                        {
                            for (int iter = 0; iter < iterations; iter++)
                            {
                                Task <int> sendTask = accepted.SendAsync(new ArraySegment <byte>(writeBuffer, iter * writeBufferSize, writeBufferSize), SocketFlags.None);
                                await await Task.WhenAny(clientReceives, sendTask);

                                Assert.Equal(writeBufferSize, await sendTask);
                            }
                        }

                        await clientReceives;
                    }

                Assert.Equal(writeBuffer.Length, readData.Length);
                AssertExtensions.SequenceEqual(writeBuffer, readData.ToArray());
            }
            finally
            {
                try { File.Delete(path); }
                catch { }
            }
        }
示例#26
0
 internal virtual string GetDisplayName()
 {
     return(EndPoint switch {
         IPEndPoint _ => $"{Scheme}://{IPEndPoint}",
         UnixDomainSocketEndPoint _ => $"{Scheme}://unix:{EndPoint}",
         FileHandleEndPoint _ => $"{Scheme}://<file handle>",
         _ => throw new InvalidOperationException()
     });
示例#27
0
        public static void FromUDS()
        {
            var endpoint = new UnixDomainSocketEndPoint("/path");
            var id       = ClusterMemberId.FromEndPoint(endpoint).ToString();

            True(ClusterMemberId.TryParse(id, out var actual));
            Equal(ClusterMemberId.FromEndPoint(endpoint), actual);
        }
        private async Task <Socket> GetConnectedSocketAsync()
        {
            var endpoint = new UnixDomainSocketEndPoint(this.providerUri.LocalPath);
            var socket   = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
            await socket.ConnectAsync(endpoint);

            return(socket);
        }
示例#29
0
 // to avoid random names in TheoryData, we replace the path in test code:
 private static EndPoint RecreateUdsEndpoint(EndPoint endPoint)
 {
     if (endPoint is UnixDomainSocketEndPoint)
     {
         endPoint = new UnixDomainSocketEndPoint($"{Path.GetTempPath()}/{Guid.NewGuid()}");
     }
     return(endPoint);
 }
 public override async Task<Stream> Open(string address)
 {
     var endPoint = new UnixDomainSocketEndPoint("/tmp/" + address);
     _socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Unspecified);
     await _socket.ConnectAsync(endPoint).ConfigureAwait(false);
     _networkStream = new NetworkStream(_socket);
     return _networkStream;
 }
示例#31
0
        public EndPoint Bind(UnixDomainSocketEndPoint unixDomainSocketEndPoint, ChannelWriter <ConnectionContext> acceptQueue)
        {
            var context = AcceptSocket.Bind(unixDomainSocketEndPoint, acceptQueue, _options);

            Bind(context);

            return(context.EndPoint);
        }
示例#32
0
 /// <summary>
 /// Creates the socket used to listen for incoming connections
 /// </summary>
 private UvStreamHandle CreateListenSocket()
 {
     return(EndPoint switch
     {
         IPEndPoint _ => ListenTcp(false),
         UnixDomainSocketEndPoint _ => ListenPipe(false),
         FileHandleEndPoint _ => ListenHandle(),
         _ => throw new NotSupportedException()
     });
示例#33
0
        public async Task Socket_ConnectAsyncUnixDomainSocketEndPoint_Success()
        {
            string path = null;
            SocketTestServer server = null;
            UnixDomainSocketEndPoint endPoint = null;

            for (int attempt = 0; attempt < 5; attempt++)
            {
                path = GetRandomNonExistingFilePath();
                endPoint = new UnixDomainSocketEndPoint(path);
                try
                {
                    server = SocketTestServer.SocketTestServerFactory(endPoint, ProtocolType.Unspecified);
                    break;
                }
                catch (SocketException)
                {
                    //Path selection is contingent on a successful Bind().
                    //If it fails, the next iteration will try another path.
                }
            }

            try
            {
                Assert.NotNull(server);

                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.RemoteEndPoint = endPoint;
                args.Completed += (s, e) => ((TaskCompletionSource<bool>)e.UserToken).SetResult(true);

                var complete = new TaskCompletionSource<bool>();
                args.UserToken = complete;

                using (Socket sock = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                {
                    Assert.True(sock.ConnectAsync(args));

                    await complete.Task;

                    Assert.Equal(SocketError.Success, args.SocketError);
                    Assert.Null(args.ConnectByNameError);
                }
            }
            finally
            {
                server.Dispose();

                try { File.Delete(path); }
                catch { }
            }
        }
示例#34
0
        public void Socket_ConnectAsyncUnixDomainSocketEndPoint_Success()
        {
            string path = null;
            SocketTestServer server = null;
            UnixDomainSocketEndPoint endPoint = null;

            for (int attempt = 0; attempt < 5; attempt++)
            {
                path = GetRandomNonExistingFilePath();
                endPoint = new UnixDomainSocketEndPoint(path);
                try
                {
                    server = SocketTestServer.SocketTestServerFactory(endPoint, ProtocolType.Unspecified);
                    break;
                }
                catch (SocketException)
                {
                    // Path selection is contingent on a successful Bind(). 
                    // If it fails, the next iteration will try another path.
                }
            }

            try
            {
                Assert.NotNull(server);

                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.RemoteEndPoint = endPoint;
                args.Completed += OnConnectAsyncCompleted;

                ManualResetEvent complete = new ManualResetEvent(false);
                args.UserToken = complete;

                Socket sock = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
                Assert.True(sock.ConnectAsync(args));

                complete.WaitOne();

                Assert.Equal(SocketError.Success, args.SocketError);
                Assert.Null(args.ConnectByNameError);

                complete.Dispose();
                sock.Dispose();
                server.Dispose();
            }
            finally
            {
                File.Delete(path);
            }
        }
示例#35
0
        public void Socket_ConnectAsyncUnixDomainSocketEndPoint_NotServer()
        {
            string path = GetRandomNonExistingFilePath();
            var endPoint = new UnixDomainSocketEndPoint(path);

            SocketAsyncEventArgs args = new SocketAsyncEventArgs();
            args.RemoteEndPoint = endPoint;
            args.Completed += OnConnectAsyncCompleted;

            ManualResetEvent complete = new ManualResetEvent(false);
            args.UserToken = complete;

            Socket sock = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);

            bool willRaiseEvent = sock.ConnectAsync(args);
            if (willRaiseEvent)
            {
                complete.WaitOne();
            }

            Assert.Equal(SocketError.SocketError, args.SocketError);

            complete.Dispose();
            sock.Dispose();
        }
示例#36
0
        public async Task Socket_SendReceiveAsync_Success()
        {
            string path = GetRandomNonExistingFilePath();
            var endPoint = new UnixDomainSocketEndPoint(path);
            try
            {
                using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                {
                    server.Bind(endPoint);
                    server.Listen(1);

                    await client.ConnectAsync(endPoint);
                    using (Socket accepted = await server.AcceptAsync())
                    {
                        var data = new byte[1];
                        for (int i = 0; i < 10; i++)
                        {
                            data[0] = (byte)i;

                            await accepted.SendAsync(new ArraySegment<byte>(data), SocketFlags.None);
                            data[0] = 0;

                            Assert.Equal(1, await client.ReceiveAsync(new ArraySegment<byte>(data), SocketFlags.None));
                            Assert.Equal(i, data[0]);
                        }
                    }
                }
            }
            finally
            {
                try { File.Delete(path); }
                catch { }
            }
        }
示例#37
0
        public async Task Socket_ConnectAsyncUnixDomainSocketEndPoint_NotServer()
        {
            string path = GetRandomNonExistingFilePath();
            var endPoint = new UnixDomainSocketEndPoint(path);
            try
            {
                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.RemoteEndPoint = endPoint;
                args.Completed += (s, e) => ((TaskCompletionSource<bool>)e.UserToken).SetResult(true);

                var complete = new TaskCompletionSource<bool>();
                args.UserToken = complete;

                using (Socket sock = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                {
                    bool willRaiseEvent = sock.ConnectAsync(args);
                    if (willRaiseEvent)
                    {
                        await complete.Task;
                    }

                    Assert.Equal(SocketError.SocketError, args.SocketError);
                }
            }
            finally
            {
                try { File.Delete(path); }
                catch { }
            }
        }