Ooui-tws-port/Ooui/Server.cs

266 lines
10 KiB
C#
Raw Normal View History

2017-06-12 22:17:23 +00:00
using System;
2017-06-12 23:24:40 +00:00
using System.Collections.Generic;
using System.IO;
2017-06-12 22:17:23 +00:00
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.Net.WebSockets;
namespace Ooui
{
public class Server
{
2017-06-12 23:24:40 +00:00
readonly Dictionary<string, Func<Element>> publishedPaths =
new Dictionary<string, Func<Element>> ();
2017-06-13 01:24:30 +00:00
readonly static byte[] clientJsBytes;
static Server ()
{
var asm = typeof(Server).Assembly;
2017-06-13 02:54:47 +00:00
// System.Console.WriteLine("ASM = {0}", asm);
// foreach (var n in asm.GetManifestResourceNames()) {
// System.Console.WriteLine(" {0}", n);
// }
2017-06-13 01:24:30 +00:00
using (var s = asm.GetManifestResourceStream ("Ooui.Client.js")) {
using (var r = new StreamReader (s)) {
clientJsBytes = Encoding.UTF8.GetBytes (r.ReadToEnd ());
}
}
}
2017-06-12 22:17:23 +00:00
public Task RunAsync (string listenerPrefix)
{
return RunAsync (listenerPrefix, CancellationToken.None);
}
public async Task RunAsync (string listenerPrefix, CancellationToken token)
{
2017-06-13 02:54:47 +00:00
HttpListener listener = null;
var started = false;
while (!started) {
try {
listener = new HttpListener ();
listener.Prefixes.Add (listenerPrefix);
listener.Start ();
started = true;
}
catch (System.Net.Sockets.SocketException ex) when
(ex.SocketErrorCode == System.Net.Sockets.SocketError.AddressAlreadyInUse) {
var wait = 5;
Console.WriteLine ($"{listenerPrefix} is in use, trying again in {wait} seconds...");
await Task.Delay (wait * 1000);
}
}
Console.ForegroundColor = ConsoleColor.Green;
2017-06-12 22:17:23 +00:00
Console.WriteLine ($"Listening at {listenerPrefix}...");
2017-06-13 02:54:47 +00:00
Console.ResetColor ();
2017-06-12 22:17:23 +00:00
while (!token.IsCancellationRequested) {
2017-06-12 23:24:40 +00:00
var listenerContext = await listener.GetContextAsync ().ConfigureAwait (false);
2017-06-12 22:17:23 +00:00
if (listenerContext.Request.IsWebSocketRequest) {
ProcessWebSocketRequest (listenerContext, token);
}
else {
2017-06-12 23:24:40 +00:00
ProcessRequest (listenerContext, token);
}
}
}
public void Publish (string path, Func<Element> elementCtor)
{
System.Console.WriteLine($"PUBLISH {path}");
publishedPaths[path] = elementCtor;
}
public void Publish (string path, Element element)
{
Publish (path, () => element);
}
void ProcessRequest (HttpListenerContext listenerContext, CancellationToken token)
{
var url = listenerContext.Request.Url;
var path = url.LocalPath;
Console.WriteLine ($"{listenerContext.Request.HttpMethod} {url.LocalPath}");
2017-06-13 01:24:30 +00:00
var response = listenerContext.Response;
2017-06-12 23:24:40 +00:00
Func<Element> ctor;
2017-06-13 01:24:30 +00:00
if (path == "/client.js") {
response.ContentLength64 = clientJsBytes.LongLength;
response.ContentType = "application/javascript";
response.ContentEncoding = Encoding.UTF8;
2017-06-13 01:37:41 +00:00
response.AddHeader ("Cache-Control", "public, max-age=3600");
2017-06-13 01:24:30 +00:00
using (var s = response.OutputStream) {
s.Write (clientJsBytes, 0, clientJsBytes.Length);
}
}
else if (publishedPaths.TryGetValue (path, out ctor)) {
2017-06-13 02:54:47 +00:00
WriteElementHtml (path, response);
2017-06-12 23:24:40 +00:00
}
else {
2017-06-13 01:24:30 +00:00
response.StatusCode = 404;
response.Close ();
2017-06-12 23:24:40 +00:00
}
}
2017-06-13 02:54:47 +00:00
void WriteElementHtml (string elementPath, HttpListenerResponse response)
2017-06-12 23:24:40 +00:00
{
response.StatusCode = 200;
2017-06-13 01:24:30 +00:00
response.ContentType = "text/html";
response.ContentEncoding = Encoding.UTF8;
2017-06-13 01:37:41 +00:00
var html = Encoding.UTF8.GetBytes ($@"<html>
2017-06-13 02:54:47 +00:00
<head><title>{elementPath}</title></head>
<body>
<script>rootElementPath = ""{elementPath}"";</script>
<script src=""/client.js""> </script></body>
2017-06-13 01:37:41 +00:00
</html>");
response.ContentLength64 = html.LongLength;
2017-06-12 23:24:40 +00:00
using (var s = response.OutputStream) {
2017-06-13 01:37:41 +00:00
s.Write (html, 0, html.Length);
2017-06-12 22:17:23 +00:00
}
2017-06-12 23:24:40 +00:00
response.Close ();
2017-06-12 22:17:23 +00:00
}
async void ProcessWebSocketRequest (HttpListenerContext listenerContext, CancellationToken token)
{
2017-06-13 03:31:47 +00:00
//
// Find the element
//
2017-06-13 02:54:47 +00:00
var url = listenerContext.Request.Url;
var path = url.LocalPath;
Func<Element> ctor;
if (!publishedPaths.TryGetValue (path, out ctor)) {
listenerContext.Response.StatusCode = 404;
listenerContext.Response.Close ();
return;
}
Element element = null;
try {
element = ctor ();
}
catch (Exception ex) {
listenerContext.Response.StatusCode = 500;
listenerContext.Response.Close();
Error ("Failed to create element", ex);
return;
}
2017-06-13 03:31:47 +00:00
//
// Connect the web socket
//
2017-06-12 22:17:23 +00:00
WebSocketContext webSocketContext = null;
2017-06-13 03:31:47 +00:00
WebSocket webSocket = null;
2017-06-12 22:17:23 +00:00
try {
2017-06-13 01:50:48 +00:00
webSocketContext = await listenerContext.AcceptWebSocketAsync(subProtocol: "ooui-1.0").ConfigureAwait (false);
2017-06-13 03:31:47 +00:00
webSocket = webSocketContext.WebSocket;
2017-06-13 02:54:47 +00:00
Console.WriteLine ("WEBSOCKET {0}", listenerContext.Request.Url.LocalPath);
2017-06-12 22:17:23 +00:00
}
2017-06-13 02:54:47 +00:00
catch (Exception ex) {
2017-06-12 22:17:23 +00:00
listenerContext.Response.StatusCode = 500;
listenerContext.Response.Close();
2017-06-13 02:54:47 +00:00
Error ("Failed to accept WebSocket", ex);
2017-06-12 22:17:23 +00:00
return;
}
2017-06-13 03:31:47 +00:00
//
// Preparse handlers for the element
//
Action<Message> onElementMessage = async m => {
if (webSocket == null) return;
try {
await SendMessageAsync (webSocket, m, token);
}
catch (Exception ex) {
Error ("Failed to handled element message", ex);
}
};
//
// Communicate!
//
2017-06-12 22:17:23 +00:00
try {
2017-06-13 04:50:15 +00:00
//
// Send message history, start sending updates, and add it to the body
//
2017-06-13 03:31:47 +00:00
foreach (var m in element.AllMessages) {
if (webSocket.State == WebSocketState.Open) {
await SendMessageAsync (webSocket, m, token);
}
}
element.MessageLogged += onElementMessage;
2017-06-13 04:50:15 +00:00
await SendMessageAsync (webSocket, new Message {
TargetId = "document.body",
MessageType = MessageType.Call,
Key = "appendChild",
2017-06-13 07:51:24 +00:00
Value = new[] { element },
2017-06-13 04:50:15 +00:00
}, token);
//
// Listen for events
//
2017-06-12 22:17:23 +00:00
var receiveBuffer = new byte[1024];
while (webSocket.State == WebSocketState.Open && !token.IsCancellationRequested) {
var receiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), token);
if (receiveResult.MessageType == WebSocketMessageType.Close) {
2017-06-12 23:24:40 +00:00
await webSocket.CloseAsync (WebSocketCloseStatus.NormalClosure, "", token).ConfigureAwait (false);
2017-06-12 22:17:23 +00:00
}
else if (receiveResult.MessageType == WebSocketMessageType.Binary) {
2017-06-12 23:24:40 +00:00
await webSocket.CloseAsync (WebSocketCloseStatus.InvalidMessageType, "Cannot accept binary frame", token).ConfigureAwait (false);
2017-06-12 22:17:23 +00:00
}
else {
var size = receiveResult.Count;
while (!receiveResult.EndOfMessage) {
if (size >= receiveBuffer.Length) {
2017-06-12 23:24:40 +00:00
await webSocket.CloseAsync (WebSocketCloseStatus.MessageTooBig, "Message too big", token).ConfigureAwait (false);
2017-06-12 22:17:23 +00:00
return;
}
2017-06-12 23:24:40 +00:00
receiveResult = await webSocket.ReceiveAsync (new ArraySegment<byte>(receiveBuffer, size, receiveBuffer.Length - size), token).ConfigureAwait (false);
2017-06-12 22:17:23 +00:00
size += receiveResult.Count;
}
var receivedString = Encoding.UTF8.GetString (receiveBuffer, 0, size);
Console.WriteLine ("RECEIVED: {0}", receivedString);
2017-06-13 03:31:47 +00:00
// var outputBuffer = new ArraySegment<byte> (Encoding.UTF8.GetBytes ($"You said: {receivedString}"));
// await webSocket.SendAsync (outputBuffer, WebSocketMessageType.Text, true, token).ConfigureAwait (false);
2017-06-12 22:17:23 +00:00
}
}
}
2017-06-13 02:54:47 +00:00
catch (WebSocketException ex) when (ex.WebSocketErrorCode == WebSocketError.ConnectionClosedPrematurely) {
// The remote party closed the WebSocket connection without completing the close handshake.
}
catch (Exception ex) {
Error ("Failed to process web socket", ex);
2017-06-12 22:17:23 +00:00
}
finally {
2017-06-13 03:31:47 +00:00
element.MessageLogged -= onElementMessage;
2017-06-13 02:54:47 +00:00
webSocket?.Dispose ();
2017-06-12 22:17:23 +00:00
}
}
2017-06-13 02:54:47 +00:00
2017-06-13 03:31:47 +00:00
Task SendMessageAsync (WebSocket webSocket, Message message, CancellationToken token)
{
var json = Newtonsoft.Json.JsonConvert.SerializeObject (message);
var outputBuffer = new ArraySegment<byte> (Encoding.UTF8.GetBytes (json));
return webSocket.SendAsync (outputBuffer, WebSocketMessageType.Text, true, token);
}
2017-06-13 02:54:47 +00:00
void Error (string message, Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine ("{0}: {1}", message, ex);
Console.ResetColor ();
}
2017-06-12 22:17:23 +00:00
}
}