Skip to content

Instantly share code, notes, and snippets.

@atifaziz
Created July 6, 2013 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atifaziz/5940164 to your computer and use it in GitHub Desktop.
Save atifaziz/5940164 to your computer and use it in GitHub Desktop.
// https://groups.google.com/forum/#!topic/jayrock/WR7rMn0fuoc
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Jayrock.JsonRpc;
static class Program
{
static int Main(string[] args)
{
try
{
var cts = new CancellationTokenSource();
var task = RunServer(args, cts.Token);
Console.WriteLine("Press ENTER key to stop.");
Console.ReadLine();
cts.Cancel();
task.Wait();
return 0;
}
catch (Exception e)
{
Console.Error.WriteLine(e.GetBaseException().Message);
return 1;
}
}
public static Task RunServer(string[] prefixes, CancellationToken cancellationToken)
{
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
if (!HttpListener.IsSupported)
throw new NotSupportedException("Windows XP SP2 or Server 2003 is required.");
var listener = new HttpListener();
Array.ForEach(prefixes, listener.Prefixes.Add);
listener.Start();
cancellationToken.Register(listener.Stop);
Console.WriteLine("Listening...");
var tcs = new TaskCompletionSource<object>();
listener.GetContextAsync().ContinueWith(async t =>
{
try
{
while (true)
{
var context = await t;
var request = context.Request;
var dispatcher = JsonRpcDispatcherFactory.CreateDispatcher(new DemoService());
var encoding = Encoding.UTF8; // TODO Handle instead of assuming UTF-8
using (var reader = new StreamReader(request.InputStream, encoding))
using (var writer = new StringWriter())
{
dispatcher.Process(reader, writer);
writer.Flush();
var response = context.Response;
response.ContentType = "application/json";
response.ContentEncoding = encoding;
var buffer = encoding.GetBytes(writer.GetStringBuilder().ToString());
response.ContentLength64 = buffer.Length;
response.OutputStream.Write(buffer, 0, buffer.Length);
}
t = listener.GetContextAsync();
}
}
catch (Exception e)
{
listener.Close();
tcs.TrySetException(e);
}
});
return tcs.Task;
}
}
class DemoService : JsonRpcService
{
[ JsonRpcMethod("echo", Idempotent = true)]
[ JsonRpcHelp("Echoes back the object sent as input.") ]
public object Echo(object obj)
{
return obj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment