Last active
November 7, 2017 02:49
-
-
Save pcyin/0c214eb64f6e66d1a46f to your computer and use it in GitHub Desktop.
C# Standalone HTTP Json Rpc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Net; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Web; | |
using System.Threading; | |
using Newtonsoft.Json; | |
using AustinHarris.JsonRpc; | |
namespace HttpJsonRPC | |
{ | |
class Program | |
{ | |
class ExampleCalculatorService : JsonRpcService | |
{ | |
[JsonRpcMethod] | |
private double add(double l, double r) | |
{ | |
return l + r; | |
} | |
} | |
static object obj = new ExampleCalculatorService(); | |
static void Main(string[] args) | |
{ | |
var listener = new HttpListener(); | |
listener.Prefixes.Add("http://*:8080/"); | |
listener.Start(); | |
var httpRequestHandle = new Func<HttpListenerRequest, string>((request) => { | |
var task = JsonRpcProcessor.Process(request.QueryString["j"]); | |
return task.Result; | |
}); | |
while (true) | |
{ | |
ThreadPool.QueueUserWorkItem( | |
(c) => { | |
var context = c as HttpListenerContext; | |
var request = context.Request; | |
var response = context.Response; | |
try | |
{ | |
string responseText = httpRequestHandle(request); | |
byte[] buf = Encoding.UTF8.GetBytes(responseText); | |
response.ContentLength64 = buf.Length; | |
response.OutputStream.Write(buf, 0, buf.Length); | |
} | |
catch(Exception ex) | |
{ | |
Console.WriteLine(ex.Message); | |
} | |
finally | |
{ | |
response.OutputStream.Close(); | |
} | |
} | |
, listener.GetContext()); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment