Beispiel #1
0
        public void Parse(ConnectionDataEventArgs e)
        {
            Log.Verbose("RPC-client recv:\n{0}", e.Data.Dump());

            var rpcResultHandler = new AsyncCallback(
                callback =>
            {
                var asyncData = ((JsonRpcStateAsync)callback);
                var result    = asyncData.Result + "\n";  // quick hack.
                var client    = ((RPCClient)asyncData.AsyncState);
                var data      = Encoding.UTF8.GetBytes(result);
                Log.Verbose("RPC-client send:\n{0}", data.Dump());
                client.Connection.Send(data);
            });


            var line = e.Data.ToEncodedString();

            line = line.Replace("\n", ""); // quick hack!

            var async = new JsonRpcStateAsync(rpcResultHandler, this)
            {
                JsonRpc = line
            };

            JsonRpcProcessor.Process(async, this);
        }
Beispiel #2
0
 private static void ConsoleInput()
 {
     for (string line = Console.ReadLine(); !string.IsNullOrEmpty(line); line = Console.ReadLine())
     {
         JsonRpcProcessor.Process(line).ContinueWith(response => Console.WriteLine(response.Result));
     }
 }
Beispiel #3
0
        public void Start(int port)
        {
            if (IsRunning == true)
            {
                Console.WriteLine("Service already running.");
                return;
            }

            var rpcResultHandler = new AsyncCallback(state =>
            {
                var async  = ((JsonRpcStateAsync)state);
                var result = async.Result;
                var writer = ((StreamWriter)async.AsyncState);

                writer.WriteLine(result);
                writer.FlushAsync();
            });

            socketListener = new SocketListener(IPAddress.Parse("127.0.0.1"), port);
            tokenSource    = new CancellationTokenSource();

            socketListener.StartAsync((writer, line) =>
            {
                var async = new JsonRpcStateAsync(rpcResultHandler, writer)
                {
                    JsonRpc = line
                };

                JsonRpcProcessor.Process(async, writer);
            }, tokenSource.Token);

            LogManager.GetCurrentClassLogger().Info("Service started. PortNo({0})", port);
        }
Beispiel #4
0
        private static void Benchmark()
        {
            Console.WriteLine("Starting benchmark");

            var cnt        = 50;
            var iterations = 7;

            for (int iteration = 1; iteration <= iterations; iteration++)
            {
                cnt *= iteration;
                ctr  = 0;
                var            sw  = Stopwatch.StartNew();
                AutoResetEvent are = new AutoResetEvent(false);
                var            rpcResultHandler = new AsyncCallback(_ =>
                {
                    if (Interlocked.Increment(ref ctr) == cnt)
                    {
                        sw.Stop();
                        Console.WriteLine("processed {0} rpc in {1}ms for {2} rpc/sec", cnt, sw.ElapsedMilliseconds, (double)cnt * 1000d / sw.ElapsedMilliseconds);
                        are.Set();
                    }
                });

                for (int i = 0; i < cnt; i++)
                {
                    var async = new JsonRpcStateAsync(rpcResultHandler, null);
                    async.JsonRpc = "{'method':'add','params':[1,2],'id':1}";
                    JsonRpcProcessor.Process(async);
                }
                are.WaitOne();
            }


            Console.WriteLine("Finished benchmark...");
        }
Beispiel #5
0
        /// <summary>
        /// Parses the incoming data.
        /// </summary>
        /// <param name="e"></param>
        public void Parse(ConnectionDataEventArgs e)
        {
            Log.Verbose("RPC-client recv:\n{0}", e.Data.ToEncodedString());

            var rpcResultHandler = new AsyncCallback(
                callback =>
            {
                var asyncData = ((JsonRpcStateAsync)callback);
                var result    = asyncData.Result + "\n";  // quick hack.
                var response  = Encoding.UTF8.GetBytes(result);

                var context = (SocketsRpcContext)asyncData.AsyncState;
                var miner   = (StratumMiner)context.Miner;

                miner.Connection.Send(response);

                Log.Verbose("RPC-client send:\n{0}", result);
            });

            var line = e.Data.ToEncodedString();

            line = line.Replace("\n", ""); // quick hack!

            var rpcRequest = new SocketsRpcRequest(line);
            var rpcContext = new SocketsRpcContext(this, rpcRequest);

            var async = new JsonRpcStateAsync(rpcResultHandler, rpcContext)
            {
                JsonRpc = line
            };

            JsonRpcProcessor.Process(async, rpcContext);
        }
Beispiel #6
0
        /// <summary>
        /// function to process http request (only jsonrpc ones)
        /// </summary>
        /// <param name="result"></param>
        private void _processRequest(IAsyncResult result)
        {
            _ctr = 0;
            HttpListener        listener = (HttpListener)result.AsyncState;
            HttpListenerContext context  = listener.EndGetContext(result);
            HttpListenerRequest request  = context.Request;
            var    sessionId             = Handler.DefaultSessionId();
            var    toProcess             = new StreamReader(request.InputStream).ReadToEnd();
            string response = JsonRpcProcessor.Process(sessionId, toProcess).Result;

            Console.WriteLine(response);
            byte[] buffer = Encoding.UTF8.GetBytes(response);

            context.Response.ContentLength64 = buffer.Length;
            context.Response.Headers["Access-Control-Allow-Origin"]      = "*";
            context.Response.Headers["Access-Control-Allow-Credentials"] = "true";
            context.Response.Headers["Access-Control-Allow-Methods"]     = "POST";
            context.Response.Headers["Access-Control-Allow-Headers"]     = "Content-type";
            context.Response.ContentType = "application/json";
            System.IO.Stream output = context.Response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            output.Close();

            Listener.BeginGetContext(_processRequest, Listener);
        }
Beispiel #7
0
        static void Main(string[] args)
        {
            // instances des classes JsonRpcService
            MiscRequests = new MiscRequests();
            DataRequests = new DataRequests();
            //

            var rpcResultHandler = new AsyncCallback(
                state =>
            {
                var async  = ((JsonRpcStateAsync)state);
                var result = async.Result;
                var writer = ((StreamWriter)async.AsyncState);

                writer.WriteLine(result);
                writer.FlushAsync();
            });

            SocketListener.start(3333, (writer, line) =>
            {
                var async = new JsonRpcStateAsync(rpcResultHandler, writer)
                {
                    JsonRpc = line
                };
                JsonRpcProcessor.Process(async, writer);
            });
        }
Beispiel #8
0
        private static void Benchmark()
        {
            Console.WriteLine("Starting benchmark");

            var cnt        = 50;
            var iterations = 7;

            for (int iteration = 1; iteration <= iterations; iteration++)
            {
                cnt *= iteration;
                ctr  = 0;
                Task <string>[] tasks = new Task <string> [cnt];
                var             sw    = Stopwatch.StartNew();

                var sessionid = Handler.DefaultSessionId();
                for (int i = 0; i < cnt; i += 5)
                {
                    tasks[i]     = JsonRpcProcessor.Process(sessionid, "{'method':'add','params':[1,2],'id':1}");
                    tasks[i + 1] = JsonRpcProcessor.Process(sessionid, "{'method':'addInt','params':[1,7],'id':2}");
                    tasks[i + 2] = JsonRpcProcessor.Process(sessionid, "{'method':'NullableFloatToNullableFloat','params':[1.23],'id':3}");
                    tasks[i + 3] = JsonRpcProcessor.Process(sessionid, "{'method':'Test2','params':[3.456],'id':4}");
                    tasks[i + 4] = JsonRpcProcessor.Process(sessionid, "{'method':'StringMe','params':['Foo'],'id':5}");
                }
                Task.WaitAll(tasks);
                sw.Stop();
                Console.WriteLine("processed {0:N0} rpc in \t {1:N0}ms for \t {2:N} rpc/sec", cnt, sw.ElapsedMilliseconds, (double)cnt * 1000d / sw.ElapsedMilliseconds);
            }


            Console.WriteLine("Finished benchmark...");
        }
Beispiel #9
0
        public void Parse(HttpListenerContext httpContext)
        {
            try
            {
                var httpRequest = httpContext.Request;

                using (var reader = new StreamReader(httpRequest.InputStream, Encoding.UTF8))
                {
                    var line       = reader.ReadToEnd();
                    var rpcContext = new GetworkContext(this, httpContext);

                    _packetLogger.Verbose("rx: {0}", line.PrettifyJson());

                    var async = new JsonRpcStateAsync(_rpcResultHandler, rpcContext)
                    {
                        JsonRpc = line
                    };
                    JsonRpcProcessor.Process(Pool.Config.Coin.Name, async, rpcContext);
                }
            }
            catch (JsonReaderException e) // if client sent an invalid message
            {
                _logger.Error("Skipping invalid json-rpc request - {0:l}", e.Message);
            }
        }
Beispiel #10
0
            protected override void WorkAction()
            {
                try
                {
                    var context = this.httpListener.GetContext();

                    var reader = new StreamReader(context.Request.InputStream, Encoding.UTF8);
                    var line   = reader.ReadToEnd();

                    var async = new JsonRpcStateAsync(RpcResultHandler, context.Response)
                    {
                        JsonRpc = line
                    };
                    JsonRpcProcessor.Process(async, this.rpcServer);
                }
                catch (HttpListenerException)
                {
                    // ignore the exception if the worker is stopped
                    // HttpListenerException will be thrown on SubStop
                    if (this.IsStarted)
                    {
                        throw;
                    }
                }
                finally
                {
                    // always notify to continue accepting connections
                    this.NotifyWork();
                }
            }
        /// <summary>
        /// Initiates an asynchronous call to the HTTP handler.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        /// <param name="cb">The <see cref="T:System.AsyncCallback"/> to call when the asynchronous method call is complete. If <paramref name="cb"/> is null, the delegate is not called.</param>
        /// <param name="extraData">Any extra data needed to process the request.</param>
        /// <returns>
        /// An <see cref="T:System.IAsyncResult"/> that contains information about the status of the process.
        /// </returns>
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            var async = new JsonRpcStateAsync(cb, context);

            async.JsonRpc = GetJsonRpcString(context.Request);
            JsonRpcProcessor.Process(GetSessionId(), async, context.Request);
            return(async);
        }
Beispiel #12
0
        private void testlog_Click(object sender, RoutedEventArgs e)
        {
            var async = new JsonRpcStateAsync(rpcResultHandler, null);

            // async.JsonRpc = "{'method':'add','params':[11,2],'id':1}";
            //async.JsonRpc = "{'method':'getPoints','params':[],'id':2}";
            async.JsonRpc = "{'method':'setPoints','params':[[40,-74, 40.11, -74.11]],'id':3}";
            JsonRpcProcessor.Process(async);

            return;
        }
Beispiel #13
0
        private static void ConsoleInput()
        {
            var rpcResultHandler = new AsyncCallback(_ => Console.WriteLine(((JsonRpcStateAsync)_).Result));

            for (string line = Console.ReadLine(); !string.IsNullOrEmpty(line); line = Console.ReadLine())
            {
                var async = new JsonRpcStateAsync(rpcResultHandler, null);
                async.JsonRpc = line;
                JsonRpcProcessor.Process(async);
            }
        }
Beispiel #14
0
        /// <summary>
        /// 开始异步请求
        /// </summary>
        /// <param name="context"></param>
        /// <param name="cb"></param>
        /// <param name="extraData"></param>
        /// <returns></returns>
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            context.Response.ContentType = "application/json";

            //此处将HttpContext作为附加数据传入,由End时取出得到Request返回
            var stateAsync = new JsonRpcStateAsync(cb, context);

            stateAsync.JsonRpc = GetJsonRpcString(context.Request);
            JsonRpcProcessor.Process(stateAsync, context);
            return(stateAsync);
        }
        /// <summary>
        /// Called when this WebSockets Server receives a full message (EndOfMessage) form a WebSockets client.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="rxBuffer">The rx buffer.</param>
        /// <param name="rxResult">The rx result.</param>
        protected override void OnMessageReceived(WebSocketContext context, byte[] rxBuffer, WebSocketReceiveResult rxResult)
        {
            var rpcResultHandler = new AsyncCallback(
                _ => this.Send(context, ((JsonRpcStateAsync)_).Result));

            var async = new JsonRpcStateAsync(rpcResultHandler, null)
            {
                JsonRpc = Encoding.UTF8.GetString(rxBuffer)
            };

            JsonRpcProcessor.Process(async);
        }
Beispiel #16
0
        public void MiningSubscribe_WithSessionId_ShouldEqual()
        {
            _poolConfig.Coin.Name.Returns("session");
            var service = new StratumService(_poolConfig, _shareManager);

            const string request        = @"{ 'id' : 1, 'method' : 'mining.subscribe', 'params' : [ 'cgminer/3.7.2', '02000000b507a8fd1ea2b7d9cdec867086f6935228aba1540154f83930377ea5a2e37108' ] }";
            const string expectedResult = "{\"jsonrpc\":\"2.0\",\"result\":[[\"mining.set_difficulty\",\"0\",\"mining.notify\",\"0\"],\"00000000\",4],\"id\":1}";

            var task = JsonRpcProcessor.Process(_poolConfig.Coin.Name, request, _stratumContext);

            task.Wait();

            task.Result.Should().Equal(expectedResult);
        }
Beispiel #17
0
        public void MiningSubscribe_WithSignature_ShouldEqual()
        {
            _poolConfig.Coin.Name.Returns("signature");
            var service = new StratumService(_poolConfig, _shareManager);

            const string request        = @"{ 'id' : 1, 'method' : 'mining.subscribe', 'params' : [ 'cgminer/3.7.2' ] }";
            const string expectedResult = "{\"jsonrpc\":\"2.0\",\"result\":[[\"mining.set_difficulty\",\"0\",\"mining.notify\",\"0\"],\"00000000\",4],\"id\":1}";

            var task = JsonRpcProcessor.Process(_poolConfig.Coin.Name, request, _stratumContext);

            task.Wait();

            task.Result.Should().Equal(expectedResult);
        }
Beispiel #18
0
 private void HandleReceivedMessage(object sender, SLHWebSocketServer.MessageEventArgs args)
 {
     try
     {
         Task.Run(async() =>
         {
             var result = await JsonRpcProcessor.Process(SessionId, args.Message, args);
             await args.Socket.Send(result);
         });
     }
     catch (Exception ex)
     {
         Logger.Log("Failed to process message.", Helpers.LogLevel.Error, ex);
     }
 }
Beispiel #19
0
        /// <summary>
        /// The entry point of the program
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        /// <returns>The error code.</returns>
        public static int Main(string[] args)
        {
            // Create an instance of the service so it can be registered to handle requests.
            globalRpcService = new GlobalRpcService();

            // Find all registerable game classes
            var gameTypeList = (from domainAssembly in AppDomain.CurrentDomain.GetAssemblies()
                                from assemblyType in domainAssembly.GetTypes()
                                where typeof(GameRpcService).IsAssignableFrom(assemblyType)
                                where !assemblyType.IsAbstract
                                select assemblyType).ToArray();

            // And attempt to register them
            var gameList = new List <GameRpcService>();

            foreach (Type gameType in gameTypeList)
            {
                GameRpcService game = (GameRpcService)Activator.CreateInstance(gameType);
                if (Register(game))
                {
                    gameList.Add(game);
                }
            }

            var rpcResultHandler = new AsyncCallback(
                state =>
            {
                var async  = (JsonRpcStateAsync)state;
                var result = async.Result;
                var writer = (StreamWriter)async.AsyncState;

                writer.Write(result);
                writer.Flush();
            });

            SocketListener.start(
                ListenPort,
                (writer, line) =>
            {
                var async = new JsonRpcStateAsync(rpcResultHandler, writer)
                {
                    JsonRpc = line
                };
                JsonRpcProcessor.Process(async, writer);
            });

            return(0);
        }
Beispiel #20
0
        private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            string     s  = sp.ReadLine();

            Console.WriteLine("Just read:{0}", s);

            var async = new JsonRpcStateAsync(rpcResultHandler, null);

            // async.JsonRpc = "{'method':'add','params':[11,2],'id':1}";
            //async.JsonRpc = "{'method':'getPoints','params':[],'id':2}";
            async.JsonRpc = s;//  "{'method':'setPoints','params':[[40,-74, 40.11, -74.11]],'id':3}";
            JsonRpcProcessor.Process(async);


            // next i want to display the data in s in a textbox. textbox1.text=s gives a cross thread exception
        }
Beispiel #21
0
        private void JsonRpc(HttpContext ctx)
        {
            var myContext = new MusixJsonRpcContext()
            {
                User = new MyUser
                {
                    Name = ctx.Request.User.Username
                }
            };


            string jsonRpcRequest  = new StreamReader(ctx.Request.InputStream).ReadToEnd();
            string jsonRpcResponse = JsonRpcProcessor.Process(jsonRpcRequest, myContext).Result;

            byte[] buf = Encoding.UTF8.GetBytes(jsonRpcResponse);
            ctx.Response.ContentLength = buf.Length;
            ctx.Response.OutputStream.Write(buf, 0, buf.Length);
//            ctx.Finish();
        }
Beispiel #22
0
        private void handleRequest(StreamWriter writer, string line)
        {
            var rpcResultHandler = new AsyncCallback(
                state =>
            {
                var async_  = ((JsonRpcStateAsync)state);
                var result  = async_.Result;
                var writer_ = ((StreamWriter)async_.AsyncState);

                writer_.WriteLine(result);
                writer_.FlushAsync();
            });
            var async = new JsonRpcStateAsync(rpcResultHandler, writer)
            {
                JsonRpc = line
            };

            JsonRpcProcessor.Process(async, writer);
        }
Beispiel #23
0
        /// <summary>
        /// 开始异步请求
        /// </summary>
        /// <param name="context"></param>
        /// <param name="cb"></param>
        /// <param name="extraData"></param>
        /// <returns></returns>
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            if (!string.IsNullOrWhiteSpace(context.Request.ContentType))
            {
                context.Response.ContentType = context.Request.ContentType;
            }
            else
            {
                //默认采用json格式返回
                context.Response.ContentType = "application/json";
            }

            //此处将HttpContext作为附加数据传入,由End时取出得到Request返回
            var stateAsync = new JsonRpcStateAsync(cb, context);

            stateAsync.JsonRpc = GetRequestContext(context.Request);
            JsonRpcProcessor.Process(stateAsync, context);
            return(stateAsync);
        }
Beispiel #24
0
        private static void Benchmark()
        {
            Console.WriteLine("Starting benchmark");

            var cnt        = 40;
            var iterations = 7;

            for (int iteration = 1; iteration <= iterations; iteration++)
            {
                cnt *= iteration;
                ctr  = 0;
                var            sw  = Stopwatch.StartNew();
                AutoResetEvent are = new AutoResetEvent(false);

                var fn = new Action <System.Threading.Tasks.Task <String> >(_ => {
                    if (Interlocked.Increment(ref ctr) == cnt)
                    {
                        sw.Stop();
                        Console.WriteLine("processed {0} rpc in {1}ms for {2} rpc/sec", cnt, sw.ElapsedMilliseconds, (double)cnt * 1000d / sw.ElapsedMilliseconds);
                        are.Set();
                    }
                });

                var sessionid = Handler.DefaultSessionId();
                for (int i = 0; i < cnt; i += 5)
                {
                    JsonRpcProcessor.Process(sessionid, "{'method':'add','params':[1,2],'id':1}").ContinueWith(fn);

                    JsonRpcProcessor.Process(sessionid, "{'method':'addInt','params':[1,7],'id':2}").ContinueWith(fn);

                    JsonRpcProcessor.Process(sessionid, "{'method':'NullableFloatToNullableFloat','params':[1.23],'id':3}").ContinueWith(fn);

                    JsonRpcProcessor.Process(sessionid, "{'method':'Test2','params':[3.456],'id':4}").ContinueWith(fn);

                    JsonRpcProcessor.Process(sessionid, "{'method':'StringMe','params':['Foo'],'id':5}").ContinueWith(fn);
                }
                are.WaitOne();
            }


            Console.WriteLine("Finished benchmark...");
        }
Beispiel #25
0
        public async Task StartAsync()
        {
            Server = new TcpListener(IPAddress.Parse("0.0.0.0"), 9898);
            Server.Start();
            LogTo.Debug($"MediaPlayer API started");
            while (!HasExited)
            {
                try
                {
                    using (var client = await Server.AcceptTcpClientAsync())
                        using (var stream = client.GetStream())
                        {
                            LogTo.Debug("Client connected to MediaPlayer socket");

                            using (var reader = new StreamReader(stream, Encoding.UTF8))
                                using (var writer = new StreamWriter(stream, new UTF8Encoding(false)))
                                {
                                    var line = await reader.ReadLineAsync();

                                    LogTo.Debug("MediaPlayer API received data from client: " + line);

                                    var response = await JsonRpcProcessor.Process(SessionId, line);

                                    LogTo.Debug("MediaPlayer API responsded to client: " + response);

                                    await writer.WriteLineAsync(response);

                                    await writer.FlushAsync();

                                    client.Close();
                                }
                        }
                }
                catch (Exception e)
                {
                    LogTo.Debug($"MediaPlayer API caught exception {e}");
                }
            }

            LogTo.Debug("MediaPlayer API shutting down");
            Server.Stop();
        }
Beispiel #26
0
        private void ProcessRequest(string line)
        {
            try
            {
                var rpcContext = new StratumContext(this); // set the context.
                _packetLogger.Verbose("rx: {0}", line.PrettifyJson());

                var async1 = new JsonRpcStateAsync(_rpcResultHandler, rpcContext)
                {
                    JsonRpc = line
                };
                JsonRpcProcessor.Process(Pool.Config.Coin.Name, async1, rpcContext);
            }
            catch (JsonReaderException e) // if client sent an invalid message
            {
                _logger.Error("Disconnecting miner {0:l} as we recieved an invalid json-rpc request - {1:l}",
                              Username ?? Connection.RemoteEndPoint.ToString(), e.Message);

                Connection.Disconnect(); // disconnect him.
            }
        }
Beispiel #27
0
            protected override void WorkAction()
            {
                try
                {
                    var context = this.httpListener.GetContext();

                    var reader = new StreamReader(context.Request.InputStream, Encoding.UTF8);
                    var line   = reader.ReadToEnd();

                    var async = new JsonRpcStateAsync(RpcResultHandler, context.Response)
                    {
                        JsonRpc = line
                    };
                    JsonRpcProcessor.Process(async, this.rpcServer);
                }
                finally
                {
                    // always notify to continue accepting connections
                    this.NotifyWork();
                }
            }
Beispiel #28
0
        public void Parse(HttpListenerContext httpContext)
        {
            var httpRequest = httpContext.Request;

            var encoding = Encoding.UTF8;

            var rpcResultHandler = new AsyncCallback(
                callback =>
            {
                var asyncData = ((JsonRpcStateAsync)callback);

                var result  = asyncData.Result;
                var data    = Encoding.UTF8.GetBytes(result);
                var request = ((HttpRpcResponse)asyncData.AsyncState);

                request.Response.ContentType     = "application/json";
                request.Response.ContentEncoding = encoding;

                request.Response.ContentLength64 = data.Length;
                request.Response.OutputStream.Write(data, 0, data.Length);
            });

            using (var reader = new StreamReader(httpRequest.InputStream, encoding))
            {
                var line = reader.ReadToEnd();
                Log.Verbose(line.PretifyJson());
                var response = httpContext.Response;

                var rpcResponse = new HttpRpcResponse(line, response);
                var rpcContext  = new HttpRpcContext(this, rpcResponse);

                var async = new JsonRpcStateAsync(rpcResultHandler, rpcResponse)
                {
                    JsonRpc = line
                };
                JsonRpcProcessor.Process(async, rpcContext);
            }
        }
Beispiel #29
0
        /// <summary>
        /// Called when the WebSocket used in a session receives a message.
        /// </summary>
        /// <param name="e">Represents the event data passed to the OnMessage event</param>
        protected override void OnMessage(MessageEventArgs e)
        {
            Serilog.Log.Debug("Processing message");

            // Log when the message is Binary.
            if (e.IsBinary)
            {
                Serilog.Log.Verbose("Message Type is Binary");
            }

            Serilog.Log.Verbose($"Message Data: {e.Data}");

            // Configure the response behaviour for when the RPC method completes.
            var asyncState = new JsonRpcStateAsync(ar =>
            {
                // Get the JSON response from the RPC method.
                string responseString = ((JsonRpcStateAsync)ar).Result;

                // There will be no response to send for Notifications.
                if (!string.IsNullOrWhiteSpace(responseString))
                {
                    // Send the JSON response back to the server.
                    Serilog.Log.Verbose($"Sending response: {responseString}");
                    Send(responseString);
                }

                Serilog.Log.Debug("Finished processing message");
            },
                                                   null);

            // Set the JSON which represents the RPC method call.
            asyncState.JsonRpc = e.Data;

            // Execute the RPC method call asynchronously.
            JsonRpcProcessor.Process(asyncState);
        }
Beispiel #30
0
        /// <summary>
        ///   Runs the RPC server, until it receives a call of the "quit" method.
        /// </summary>
        public void Run(ADOQueryExecutor executor)
        {
            var proxy = new JsonRpcProxy(executor);


            Config.SetPostProcessHandler((JsonRequest request, JsonResponse response, object context) => {
                if (response.Error != null)
                {
                    var innerException      = (response.Error.data as Exception);
                    var errorData           = new Dictionary <string, string>();
                    errorData["stacktrace"] = innerException.StackTrace;
                    response.Error          = new JsonRpcException(-32603, innerException.Message, errorData);
                }

                return(null);
            });

            var listener = new HttpListener();

            listener.Prefixes.Add(Endpoint);
            listener.Start();

            try
            {
                executor.Open();

                while (!proxy.Finished)
                {
                    var context = listener.GetContext();
                    AddCORSHeaders(context);

                    if (context.Request.HttpMethod == "OPTIONS")
                    {
                        context.Response.StatusCode        = 200;
                        context.Response.StatusDescription = "OK";
                        context.Response.ContentLength64   = 0;
                        context.Response.OutputStream.Close();
                        Console.WriteLine("Processing CORS OPTIONS request");
                        continue;
                    }

                    if (context.Request.HttpMethod != "POST")
                    {
                        context.Response.StatusCode        = 405;
                        context.Response.StatusDescription = "Illegal Method";
                        context.Response.OutputStream.Close();
                        Console.WriteLine("Invalid request method: {}", context.Request.HttpMethod);
                        continue;
                    }

                    if (context.Request.Url.PathAndQuery != "/")
                    {
                        context.Response.StatusCode        = 404;
                        context.Response.StatusDescription = "Not Found";
                        context.Response.OutputStream.Close();
                        Console.WriteLine("Invalid request path: {}", context.Request.Url.PathAndQuery);
                        continue;
                    }

                    if (context.Request.ContentType != "application/json")
                    {
                        context.Response.StatusCode        = 400;
                        context.Response.StatusDescription = "Illegal Content Type";
                        context.Response.OutputStream.Close();
                        Console.WriteLine("Invalid request Content-Type: {}", context.Request.ContentType);
                        continue;
                    }

                    context.Response.ContentType = "application/json";
                    var inputBuffer = new byte[context.Request.ContentLength64];
                    var offset      = 0L;

                    while (offset != context.Request.ContentLength64)
                    {
                        offset += context.Request.InputStream.Read(inputBuffer, (int)offset, (int)(context.Request.ContentLength64 - offset));
                    }

                    var input = Encoding.UTF8.GetString(inputBuffer);

                    JsonRpcProcessor
                    .Process(input)
                    .ContinueWith(result => {
                        SetOutputContent(context.Response, result.Result);
                    })
                    .Wait();
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Terminating web server");
                listener.Stop();
                executor.Close();
                throw;
            }
        }