Example #1
0
        public void TestTimingThousandCalls()
        {
            JsonRpcServer server = new JsonRpcServer("nats://127.0.0.1", 5000);

            using (server)
            {
                JsonRpcRequest request = new JsonRpcRequest
                {
                    Method     = "test:channel",
                    Id         = Guid.NewGuid().ToString(),
                    Parameters = new Dictionary <string, string>
                    {
                        { "data", "ping" }
                    }
                };
                Stopwatch sw = new Stopwatch();
                sw.Start();
                for (int i = 0; i < 1000; i++)
                {
                    var resp = server.ServeAsync(request).GetAwaiter().GetResult();
                    Assert.IsNotNull(resp);
                    Assert.IsNull(resp.Error);
                    Assert.AreEqual(request.Id.ToString(), resp.Id);
                    Assert.AreEqual("ping", resp.Result);
                }
                sw.Stop();
                Console.WriteLine($"Elapsed Time:{sw.Elapsed}");
            }
        }
Example #2
0
            public CreateData()
            {
                var baseOptions = new JsonRpcServerOptions().WithPipe(new Pipe());

                void BaseDelegate(JsonRpcServerOptions o)
                {
                    o.WithPipe(new Pipe());
                }

                var serviceProvider = new ServiceCollection().BuildServiceProvider();

                Add(new ActionDelegate("create: options", () => JsonRpcServer.Create(baseOptions)));
                Add(new ActionDelegate("create: options, serviceProvider", () => JsonRpcServer.Create(baseOptions, serviceProvider)));
                Add(new ActionDelegate("create: action", () => JsonRpcServer.Create(BaseDelegate)));
                Add(new ActionDelegate("create: action, serviceProvider", () => JsonRpcServer.Create(BaseDelegate, serviceProvider)));

                Add(new ActionDelegate("from: options", () => JsonRpcServer.From(baseOptions)));
                Add(new ActionDelegate("from: options, cancellationToken", () => JsonRpcServer.From(baseOptions, CancellationToken.None)));
                Add(new ActionDelegate("from: options, serviceProvider, cancellationToken", () => JsonRpcServer.From(baseOptions, serviceProvider, CancellationToken.None)));
                Add(new ActionDelegate("from: options, serviceProvider", () => JsonRpcServer.From(baseOptions, serviceProvider)));
                Add(new ActionDelegate("from: action", () => JsonRpcServer.From(BaseDelegate)));
                Add(new ActionDelegate("from: action, cancellationToken", () => JsonRpcServer.From(BaseDelegate, CancellationToken.None)));
                Add(new ActionDelegate("from: action, serviceProvider, cancellationToken", () => JsonRpcServer.From(BaseDelegate, serviceProvider, CancellationToken.None)));
                Add(new ActionDelegate("from: action, serviceProvider", () => JsonRpcServer.From(BaseDelegate, serviceProvider)));
            }
Example #3
0
        public void TestExceptionInJsonRpcShouldReturnInternalError()
        {
            JsonRpcServer server = new JsonRpcServer("nats://127.0.0.1", 10000);

            using (server)
            {
                JsonRpcRequest request = new JsonRpcRequest
                {
                    Method     = "test:exception",
                    Id         = Guid.NewGuid().ToString(),
                    Parameters = new Dictionary <string, string>
                    {
                        { "data", "ping" }
                    }
                };
                var resp = server.ServeAsync(request).GetAwaiter().GetResult();

                Assert.IsNotNull(resp);
                Assert.AreEqual(request.Id.ToString(), resp.Id);
                Assert.IsNull(resp.Result);
                Assert.IsNotNull(resp.Error);
                Assert.AreEqual((int)ErrorCode.InternalError, resp.Error.Code);
                Assert.AreEqual("Error", resp.Error.Message);
            }
        }
Example #4
0
        public void ReturnStringArray()
        {
            Response <object> reply = default;

            var handler    = new TestHandlerFake();
            var server     = new JsonRpcServer();
            var clientMock = new Mock <JsonRpcServer.ClientConnection>(1, "localhost", _fakePipe, _process, Encoding.UTF8);

            clientMock.Setup(x => x.WriteAsJson(It.IsAny <object>())).Callback <object>(o => reply = (Response <object>)o);

            var reqOring = new Request()
            {
                Id = 3, Method = "ReturnStringArray"
            };
            var json = Serializer.Serialize(reqOring);
            var req  = Serializer.Deserialize <Request>(json);

            server.Bind(handler);
            server.ExecuteHandler(clientMock.Object, req.Id, req.Method, req.Params);

            reply.Should().NotBeNull();
            reply.Id.Should().Be(3);
            reply.Error.Should().BeNull();
            reply.Result.Should().BeEquivalentTo(new string[] { "one", "two", "three" });
        }
Example #5
0
        public void Call_GivenDateTime()
        {
            Response reply = default;

            var handler    = new TestHandlerFake();
            var server     = new JsonRpcServer();
            var clientMock = new Mock <JsonRpcServer.ClientConnection>(1, "localhost", _fakePipe, _process, Encoding.UTF8);

            clientMock.Setup(x => x.WriteAsJson(It.IsAny <object>())).Callback <object>(o => reply = (Response)o);

            var now      = DateTime.Now;
            var reqOring = new Request()
            {
                Id = 81, Method = "DateTimeTest", Params = new object[] { now }
            };
            var json = Serializer.Serialize(reqOring);
            var req  = Serializer.Deserialize <Request>(json);

            server.Bind(handler);
            server.ExecuteHandler(clientMock.Object, req.Id, req.Method, req.Params);

            reply.Should().NotBeNull();
            reply.Id.Should().Be(81);
            reply.Error.Should().BeNull();
        }
Example #6
0
        public void TestNatSubscriptionShouldLogPublishingError()
        {
            var mockLogger = new Mock <Microsoft.Extensions.Logging.ILogger>();
            JsonRpcSubscription subscription = new JsonRpcSubscription("test:largepayload", "test::group", new LargePayloadService(), mockLogger.Object);

            subscription.Subscribe("nats://127.0.0.1");
            subscription.Start().GetAwaiter().GetResult();

            JsonRpcServer server = new JsonRpcServer("nats://127.0.0.1", 5000);

            using (server)
            {
                Assert.Throws <JsonRpcException>(() =>
                {
                    var resp = server.ServeAsync(new JsonRpcRequest
                    {
                        Method     = "test:largepayload",
                        Id         = Guid.NewGuid().ToString(),
                        Parameters = new Dictionary <string, string>
                        {
                            { "size", "10000000" }
                        }
                    }).GetAwaiter().GetResult();
                });
            }

            mockLogger.Verify(m => m.Log(LogLevel.Error, It.IsAny <EventId>(), It.IsAny <Object>(), It.IsAny <Exception>(), It.IsAny <Func <Object, Exception, string> >()));
        }
Example #7
0
        public void TestMultipleConcurrentCallsShouldNotThrowException()
        {
            JsonRpcServer server = new JsonRpcServer("nats://127.0.0.1", 5000);
            List <Task>   tasks  = new List <Task>();

            for (int i = 0; i < 10; i++)
            {
                var task = Task.Run(() =>
                {
                    JsonRpcRequest request = new JsonRpcRequest
                    {
                        Method     = "test:channel",
                        Id         = Guid.NewGuid().ToString(),
                        Parameters = new Dictionary <string, string>
                        {
                            { "data", "ping" }
                        }
                    };

                    //server.ServeAsync(request).GetAwaiter().GetResult();
                });
                tasks.Add(task);
            }

            Assert.DoesNotThrow(() => { Task.WaitAll(tasks.ToArray()); });
            server.Dispose();
        }
Example #8
0
        public void CanInvokeDelegate_WithArgs_ReturnValue()
        {
            Response <object> reply = default;

            var fakePipe = new StreamDuplexPipe(PipeOptions.Default, new MemoryStream());
            var server   = new JsonRpcServer();

            var clientMock = new Mock <JsonRpcServer.ClientConnection>(1, "localhost", fakePipe, _process, Encoding.UTF8);

            clientMock.Setup(x => x.WriteAsJson(It.IsAny <object>())).Callback <object>(o => reply = (Response <object>)o);

            bool called = false;

            server.Bind("DelegateFunction", (Func <int, string, string>)((a, b) =>
            {
                called = b == "TestString";
                return(b);
            }));
            server.ExecuteHandler(clientMock.Object, 21, "DelegateFunction", new object[] { 176, "TestString" });

            called.Should().BeTrue();
            reply.Should().NotBeNull();
            reply.Error.Should().BeNull();
            reply.Id.Should().Be(21);
            reply.Result.Should().NotBeNull();
            reply.Result.Should().Be("TestString");
        }
		public JsonRpcIntegrationTestBase(ITestOutputHelper output) {
			this.output = output;

			var configs = new JsonRpcServerConfigurations() {
				BindingPort = port, //Interlocked.Increment(ref port),
				TransportProtocol = JsonRpcServerConfigurations.TransportMode.Bson
			};

			server = new JsonRpcServer<TestActionHandler>(configs);

			client = JsonRpcClient<TestActionHandler>.CreateClient("localhost", server.Configurations.BindingPort, JsonRpcServerConfigurations.TransportMode.Bson);
			client.Info.Username = "******";

			client.OnAuthenticationRequest += (sender, e) => {
				e.Data = AUTH_TEXT;
			};

			server.OnAuthenticationVerification += (sender, e) => {
				e.Authenticated = true;
			};

			server.OnStop += (sender, e) => {
				wait.Set();
			};
		}
Example #10
0
        /// <summary>
        /// Start the debug server listening.
        /// </summary>
        /// <returns>A task that completes when the server is ready.</returns>
        public async Task StartAsync()
        {
            _jsonRpcServer = await JsonRpcServer.From(options =>
            {
                options.Serializer    = new DapProtocolSerializer();
                options.Receiver      = new DapReceiver();
                options.LoggerFactory = _loggerFactory;
                ILogger logger        = options.LoggerFactory.CreateLogger("DebugOptionsStartup");

                // We need to let the PowerShell Context Service know that we are in a debug session
                // so that it doesn't send the powerShell/startDebugger message.
                _powerShellContextService = ServiceProvider.GetService <PowerShellContextService>();
                _powerShellContextService.IsDebugServerActive = true;

                // Needed to make sure PSReadLine's static properties are initialized in the pipeline thread.
                // This is only needed for Temp sessions who only have a debug server.
                if (_usePSReadLine && _useTempSession && Interlocked.Exchange(ref s_hasRunPsrlStaticCtor, 1) == 0)
                {
                    // This must be run synchronously to ensure debugging works
                    _powerShellContextService
                    .ExecuteScriptStringAsync("[System.Runtime.CompilerServices.RuntimeHelpers]::RunClassConstructor([Microsoft.PowerShell.PSConsoleReadLine].TypeHandle)")
                    .GetAwaiter()
                    .GetResult();
                }

                options.Services = new ServiceCollection()
                                   .AddPsesDebugServices(ServiceProvider, this, _useTempSession);

                options
                .WithInput(_inputStream)
                .WithOutput(_outputStream);

                logger.LogInformation("Adding handlers");

                options
                .WithHandler <InitializeHandler>()
                .WithHandler <LaunchHandler>()
                .WithHandler <AttachHandler>()
                .WithHandler <DisconnectHandler>()
                .WithHandler <SetFunctionBreakpointsHandler>()
                .WithHandler <SetExceptionBreakpointsHandler>()
                .WithHandler <ConfigurationDoneHandler>()
                .WithHandler <ThreadsHandler>()
                .WithHandler <SetBreakpointsHandler>()
                .WithHandler <StackTraceHandler>()
                .WithHandler <ScopesHandler>()
                .WithHandler <VariablesHandler>()
                .WithHandler <ContinueHandler>()
                .WithHandler <NextHandler>()
                .WithHandler <PauseHandler>()
                .WithHandler <StepInHandler>()
                .WithHandler <StepOutHandler>()
                .WithHandler <SourceHandler>()
                .WithHandler <SetVariableHandler>()
                .WithHandler <DebugEvaluateHandler>();

                logger.LogInformation("Handlers added");
            }).ConfigureAwait(false);
        }
Example #11
0
        public static string[] ListMethods(JsonRpcServer server)
        {
            var methods = server.Methods
                          .Select(m => m.Name)
                          .ToArray();

            return(methods);
        }
Example #12
0
        static void Main(string[] args)
        {
            ThreadPool.SetMinThreads(65535, 65535);
            var server = new JsonRpcServer();

            var client = new JsonRpcClient();

            if (args.Contains("-debug"))
            {
                Logger.DebugMode = true;
                Logger.UseDefaultWriter();
            }

            if (args.Contains("-benchmark"))
            {
                var engine = new JsonRpcInProcessEngine();
                server.UseEngine(engine);
                client.UseEngine(engine);
                server.Start();
                var statisticsList = new List <int>();
                for (var i = 0; i < 20; i++)
                {
                    statisticsList.Add(Benchmark(client, TestData));
                    Console.WriteLine();
                }
                Console.WriteLine();
                Console.WriteLine($"Best: {statisticsList.Max()} rpc/sec, \t Average: {(int)statisticsList.Average()} rpc/sec, \t Worst: {statisticsList.Min()} rpc/sec");
            }
            else
            {
                IJsonRpcServerEngine serverEngine;
                if (args.Contains("-websocket"))
                {
                    serverEngine = new JsonRpcWebSocketServerEngine("http://*:8090/");
                    server.UseEngine(serverEngine);
                }
                else if (args.Contains("-websocket-kestrel"))
                {
                    serverEngine = new JsonRpcKestrelWebSocketServerEngine(IPAddress.Any, 8090);
                    server.UseEngine(serverEngine);
                }
                else
                if (args.Contains("-http-kestrel"))
                {
                    serverEngine = new JsonRpcKestrelHttpServerEngine(IPAddress.Any, 8090);
                    server.UseEngine(serverEngine);
                }
                else
                {
                    serverEngine = new JsonRpcHttpServerEngine("http://*:8090/");
                    server.UseEngine(serverEngine);
                }

                server.Start();
                Console.WriteLine($"JsonRpc Server Started with engine: {serverEngine.Name}.");
            }
            Console.ReadLine();
        }
Example #13
0
        protected virtual async Task <(JsonRpcServer client, JsonRpcServer server)> Initialize(
            Action <JsonRpcServerOptions> clientOptionsAction,
            Action <JsonRpcServerOptions> serverOptionsAction
            )
        {
            var clientPipe = new Pipe(TestOptions.DefaultPipeOptions);
            var serverPipe = new Pipe(TestOptions.DefaultPipeOptions);

            var clientTask = JsonRpcServer.From(
                options => {
                options
                .WithLoggerFactory(TestOptions.ClientLoggerFactory)
                .WithServices(
                    services => services
                    .AddTransient(typeof(IPipelineBehavior <,>), typeof(SettlePipeline <,>))
                    .AddSingleton(ClientEvents as IRequestSettler)
                    .AddLogging(
                        x => {
                    x.SetMinimumLevel(LogLevel.Trace);
                }
                        )
                    );
                ConfigureClientInputOutput(serverPipe.Reader, clientPipe.Writer, options);
                clientOptionsAction(options);
            }, CancellationToken
                );

            var serverTask = JsonRpcServer.From(
                options => {
                options
                .WithServices(
                    services => services
                    .AddTransient(typeof(IPipelineBehavior <,>), typeof(SettlePipeline <,>))
                    .AddSingleton(ServerEvents as IRequestSettler)
                    .AddLogging(
                        x => {
                    x.SetMinimumLevel(LogLevel.Trace);
                    x.Services.AddSingleton(TestOptions.ServerLoggerFactory);
                }
                        )
                    );
                ConfigureServerInputOutput(clientPipe.Reader, serverPipe.Writer, options);
                serverOptionsAction(options);
            }, CancellationToken
                );

            await Task.WhenAll(clientTask, serverTask).ConfigureAwait(false);

#pragma warning disable VSTHRD103
            _client = clientTask.Result;
            _server = serverTask.Result;
#pragma warning restore VSTHRD103

            Disposable.Add(_client);
            Disposable.Add(_server);

            return(_client, _server);
        }
        public TestRpcClient()
        {
            var glue = new MockService();

            var listener = new JsonRpcServer(glue);

            listener.Register <RpcTargetMock>();
            listener.Start();

            _client = new JsonRpcClient(glue);
        }
Example #15
0
        public void TestTypeRegistration()
        {
            using (new AssertionScope())
                using (var listener = new JsonRpcServer(new MockService()))
                {
                    listener.Register(typeof(RpcTargetMock));

                    var registry = listener.GetRegisteredMethods();

                    registry.Should().Contain("Canary");
                }
        }
        public async Task StartAsync(IServiceProvider languageServerServiceProvider, bool useTempSession)
        {
            _jsonRpcServer = await JsonRpcServer.From(options =>
            {
                options.Serializer    = new DapProtocolSerializer();
                options.Reciever      = new DapReciever();
                options.LoggerFactory = _loggerFactory;
                ILogger logger        = options.LoggerFactory.CreateLogger("DebugOptionsStartup");

                // We need to let the PowerShell Context Service know that we are in a debug session
                // so that it doesn't send the powerShell/startDebugger message.
                _powerShellContextService = languageServerServiceProvider.GetService <PowerShellContextService>();
                _powerShellContextService.IsDebugServerActive = true;

                // Needed to make sure PSReadLine's static properties are initialized in the pipeline thread.
                _powerShellContextService
                .ExecuteScriptStringAsync("[System.Runtime.CompilerServices.RuntimeHelpers]::RunClassConstructor([Microsoft.PowerShell.PSConsoleReadLine].TypeHandle)")
                .Wait();

                options.Services = new ServiceCollection()
                                   .AddPsesDebugServices(languageServerServiceProvider, this, useTempSession);

                options
                .WithInput(_inputStream)
                .WithOutput(_outputStream);

                logger.LogInformation("Adding handlers");

                options
                .WithHandler <InitializeHandler>()
                .WithHandler <LaunchHandler>()
                .WithHandler <AttachHandler>()
                .WithHandler <DisconnectHandler>()
                .WithHandler <SetFunctionBreakpointsHandler>()
                .WithHandler <SetExceptionBreakpointsHandler>()
                .WithHandler <ConfigurationDoneHandler>()
                .WithHandler <ThreadsHandler>()
                .WithHandler <SetBreakpointsHandler>()
                .WithHandler <StackTraceHandler>()
                .WithHandler <ScopesHandler>()
                .WithHandler <VariablesHandler>()
                .WithHandler <ContinueHandler>()
                .WithHandler <NextHandler>()
                .WithHandler <PauseHandler>()
                .WithHandler <StepInHandler>()
                .WithHandler <StepOutHandler>()
                .WithHandler <SourceHandler>()
                .WithHandler <SetVariableHandler>()
                .WithHandler <DebugEvaluateHandler>();

                logger.LogInformation("Handlers added");
            });
        }
Example #17
0
        public void NoReturnOnNotify()
        {
            string reply = null;

            var handler    = new TestHandlerFake();
            var server     = new JsonRpcServer();
            var clientMock = new Mock <JsonRpcServer.ClientConnection>(1, "localhost", _fakePipe, _process, Encoding.UTF8);

            clientMock.Setup(x => x.WriteString(It.IsAny <string>())).Callback <string>(s => reply = s);

            server.Bind(handler);
            server.ExecuteHandler(clientMock.Object, -1, "ReturnStringArray", null);

            reply.Should().BeNull();
        }
Example #18
0
            public MissingOutputData()
            {
                var baseOptions = new JsonRpcServerOptions().WithInput(new Pipe().Reader);

                void BaseDelegate(JsonRpcServerOptions o)
                {
                    o.WithInput(new Pipe().Reader);
                }

                var serviceProvider = new ServiceCollection().BuildServiceProvider();

                Add(new ActionDelegate("create: options", () => JsonRpcServer.Create(baseOptions)));
                Add(new ActionDelegate("create: options, serviceProvider", () => JsonRpcServer.Create(baseOptions, serviceProvider)));
                Add(new ActionDelegate("create: action", () => JsonRpcServer.Create(BaseDelegate)));
                Add(new ActionDelegate("create: action, serviceProvider", () => JsonRpcServer.Create(BaseDelegate, serviceProvider)));
            }
Example #19
0
        public void Awake()
        {
            SceneDumpService = new SceneDumpService(new RuntimeObjectWrapperService());

            Processor    = new JsonRpcProcessor();
            QueryService = new SceneQueryService();
            LuaRuntime   = new DefaultUnitiniumLuaRuntime(QueryService);

            Processor.SetMethod("dump", SceneDumpService.DumpScenes);
            Processor.SetMethod("execute", (string script) => LuaRuntime.Execute(script));
            Processor.SetMethod("co_execute", (string script) => LuaRuntime.Execute(script, true));
            Processor.SetMethod("get_execution", (long id) => LuaRuntime.GetExecution((int)id));
            Processor.SetMethod("query", (string query) => QueryService.Execute(query));

            server   = new JsonRpcServer();
            requests = server.Start("http://localhost:" + ListenPort + "/");
        }
Example #20
0
        public void Call_WithDefaultArgsValues()
        {
            Response reply = default;

            var handler    = new TestHandlerFake();
            var server     = new JsonRpcServer();
            var clientMock = new Mock <JsonRpcServer.ClientConnection>(1, "localhost", _fakePipe, _process, Encoding.UTF8);

            clientMock.Setup(x => x.WriteAsJson(It.IsAny <object>())).Callback <object>(o => reply = (Response)o);

            server.Bind(handler);
            server.ExecuteHandler(clientMock.Object, 31, "DefaultArgs", new object[] { 123 });

            reply.Should().NotBeNull();
            reply.Id.Should().Be(31);
            reply.Error.Should().BeNull();
        }
Example #21
0
        public void TestDisposedServiceThrowsException()
        {
            JsonRpcServer server = new JsonRpcServer("nats://127.0.0.1", 5000);

            server.Dispose();
            JsonRpcRequest request = new JsonRpcRequest
            {
                Method     = "test:channel",
                Id         = Guid.NewGuid().ToString(),
                Parameters = new Dictionary <string, string>
                {
                    { "data", "ping" }
                }
            };

            Assert.Throws <ObjectDisposedException>(() => server.Serve(request));
        }
Example #22
0
        public void Call_GivenTypesArgs()
        {
            Response <object> reply = default;

            var handler    = new TestHandlerFake();
            var server     = new JsonRpcServer();
            var clientMock = new Mock <JsonRpcServer.ClientConnection>(1, "localhost", _fakePipe, _process, Encoding.UTF8);

            clientMock.Setup(x => x.WriteAsJson(It.IsAny <object>())).Callback <object>(o => reply = (Response <object>)o);

            server.Bind(handler);
            server.ExecuteHandler(clientMock.Object, 1, "FirstTest", new object[] { 1, "string", false, null });

            reply.Should().NotBeNull();
            reply.Id.Should().Be(1);
            reply.Result.Should().Be(23);
        }
Example #23
0
        public void Call_StaticFunction()
        {
            Response reply = default;

            var fakePipe = new StreamDuplexPipe(PipeOptions.Default, new MemoryStream());
            var server   = new JsonRpcServer();

            var clientMock = new Mock <JsonRpcServer.ClientConnection>(1, "localhost", fakePipe, _process, Encoding.UTF8);

            clientMock.Setup(x => x.WriteAsJson(It.IsAny <object>())).Callback <object>(o => reply = (Response)o);

            server.Bind(typeof(StaticHandler));
            server.ExecuteHandler(clientMock.Object, 43, "Function1", null);

            reply.Should().NotBeNull();
            reply.Error.Should().BeNull();
        }
Example #24
0
        public JsonRpcContext(IServiceProvider requestServices, JsonRpcServer server, JsonRpcRequest request)
        {
            if (requestServices == null)
            {
                throw new ArgumentNullException(nameof(requestServices));
            }
            if (server == null)
            {
                throw new ArgumentNullException(nameof(server));
            }
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            RequestServices = requestServices;
            Server          = server;
            Request         = request;
        }
Example #25
0
        public void TestTypeRegistrationExplicit()
        {
            using (new AssertionScope())
                using (var listener = new JsonRpcServer(new MockService()))
                {
                    listener.Register(typeof(RpcTargetMock), "Canary");
                    listener.Register(typeof(RpcTargetMock), "Echo", "Pizza");

                    var registry = listener.GetRegisteredMethods();

                    registry.Should().Contain("Canary");
                    registry.Should().Contain("Pizza");

                    // ReSharper disable once AccessToDisposedClosure
                    Action testAction = () => listener.Register(typeof(RpcTargetMock), "thisIsNotAValidMethod");

                    testAction.Should().Throw <RpcRegistrationException>();
                }
        }
Example #26
0
        static void Main(string[] args)
        {
            Console.WriteLine("JSON RPC SimpleServer\n");

            _server = new JsonRpcServer();

            _listener = new TcpListener(IPAddress.Any, 11000);
            _listener.Start();

            // Accept first client connection
            _listener.BeginAcceptTcpClient(AcceptClient, null);

            Console.WriteLine($"Listening on port 11000");
            Console.WriteLine("Press ENTER to stop\n");
            Console.ReadLine();

            _listener.Stop();
            _server.Dispose();
        }
Example #27
0
        public void TestCallUnknownMethodCallTimeout()
        {
            JsonRpcServer server = new JsonRpcServer("nats://127.0.0.1", 5000);

            using (server)
            {
                JsonRpcRequest request = new JsonRpcRequest
                {
                    Method     = "test:channel-unknown",
                    Id         = Guid.NewGuid().ToString(),
                    Parameters = new Dictionary <string, string>
                    {
                        { "data", "ping" }
                    }
                };
                Stopwatch sw = Stopwatch.StartNew();
                Assert.Throws <JsonRpcException>(() => server.ServeAsync(request).GetAwaiter().GetResult());
                sw.Stop();
                Assert.IsTrue(sw.ElapsedMilliseconds >= 5000);
            }
        }
Example #28
0
        public void CanInvokeDelegate()
        {
            Response reply = default;

            var fakePipe = new StreamDuplexPipe(PipeOptions.Default, new MemoryStream());
            var server   = new JsonRpcServer();

            var clientMock = new Mock <JsonRpcServer.ClientConnection>(1, "localhost", fakePipe, _process, Encoding.UTF8);

            clientMock.Setup(x => x.WriteAsJson(It.IsAny <object>())).Callback <object>(o => reply = (Response)o);

            bool called = false;

            server.Bind("DelegateFunction", (Action)(() => { called = true; }));
            server.ExecuteHandler(clientMock.Object, 43, "DelegateFunction", null);

            called.Should().BeTrue();
            reply.Should().NotBeNull();
            reply.Error.Should().BeNull();
            reply.Id.Should().Be(43);
        }
Example #29
0
        public void TestNatSubscriptionShouldRecoverFromPublishingError()
        {
            JsonRpcSubscription subscription = new JsonRpcSubscription("test:largepayload", "test::group", new LargePayloadService(), null);

            subscription.Subscribe("nats://127.0.0.1");
            subscription.Start().GetAwaiter().GetResult();

            JsonRpcServer server = new JsonRpcServer("nats://127.0.0.1", 5000);

            using (server)
            {
                Assert.Throws <JsonRpcException>(() =>
                {
                    var resp = server.ServeAsync(new JsonRpcRequest
                    {
                        Method     = "test:largepayload",
                        Id         = Guid.NewGuid().ToString(),
                        Parameters = new Dictionary <string, string>
                        {
                            { "size", "10000000" }
                        }
                    }).GetAwaiter().GetResult();
                });

                var resp2 = server.ServeAsync(new JsonRpcRequest
                {
                    Method     = "test:largepayload",
                    Id         = Guid.NewGuid().ToString(),
                    Parameters = new Dictionary <string, string>
                    {
                        { "size", "100" }
                    }
                }).GetAwaiter().GetResult();

                Assert.IsNotNull(resp2);
                Assert.IsNull(resp2.Error);
                Assert.AreEqual(resp2.Id.ToString(), resp2.Id);
                Assert.AreEqual(new string('A', 100), resp2.Result);
            }
        }
Example #30
0
        public void TestCallMethodOverJsonRpc()
        {
            JsonRpcServer server = new JsonRpcServer("nats://127.0.0.1", 5000);

            using (server)
            {
                JsonRpcRequest request = new JsonRpcRequest
                {
                    Method     = "test:channel",
                    Id         = Guid.NewGuid().ToString(),
                    Parameters = new Dictionary <string, string>
                    {
                        { "data", "ping" }
                    }
                };
                var resp = server.ServeAsync(request).GetAwaiter().GetResult();
                Assert.IsNotNull(resp);
                Assert.IsNull(resp.Error);
                Assert.AreEqual(request.Id.ToString(), resp.Id);
                Assert.AreEqual("ping", resp.Result);
            }
        }
Example #31
0
        public void Call_GivenIntStringBoolNull()
        {
            Response <object> reply = default;

            var handler    = new TestHandlerFake();
            var server     = new JsonRpcServer();
            var clientMock = new Mock <JsonRpcServer.ClientConnection>(1, "localhost", _fakePipe, _process, Encoding.UTF8);

            clientMock.Setup(x => x.WriteAsJson(It.IsAny <object>())).Callback <object>(o => reply = (Response <object>)o);

            var reqOring = new Request()
            {
                Id = 1, Method = "FirstTest", Params = new object[] { 1, "string", false, null }
            };
            var json = Serializer.Serialize(reqOring);
            var req  = Serializer.Deserialize <Request>(json);

            server.Bind(handler);
            server.ExecuteHandler(clientMock.Object, req.Id, req.Method, req.Params);

            reply.Should().NotBeNull();
            reply.Id.Should().Be(1);
            reply.Result.Should().Be(23);
        }
		public async void Ping_does_not_time_out() {
			server.Configurations.PingFrequency = 250;
			server.Configurations.PingTimeoutDisconnectTime = 500;

			server = new JsonRpcServer<TestActionHandler>(server.Configurations);
			server.OnClientConnect += (sender, e) => {

				Task.Run(async () => {
					await Task.Delay(1000);

					if (e.Client.Info.Status == ClientStatus.Connected) {
						CompleteTest();
					} else {
						FailTest();
					}
				});
			};

			server.Start();
			client.Connect();

			await StartAndWaitClient();
		}
		public async void Ping_client_times_out() {
			server.Configurations.PingFrequency = 250;
			server.Configurations.PingTimeoutDisconnectTime = 500;
			server = new JsonRpcServer<TestActionHandler>(server.Configurations);



			server.OnClientConnect += (sender, e) => {

				// Make the remote client ignore all incoming requests.
				e.Client.OnDataReceived += (s2, e2) => {
					e2.Handled = true;
				};
			};

			server.OnClientDisconnect += (sender, e) => {
				CompleteTest();
			};

			server.Start();

			client.Connect();

			await StartAndWaitClient();
		}