2017-06-14 01:37:03 +00:00
|
|
|
using System;
|
2017-06-15 07:40:08 +00:00
|
|
|
using System.Collections.Generic;
|
|
|
|
using System.IO;
|
|
|
|
using System.Text;
|
|
|
|
using System.Threading;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
using System.Net;
|
|
|
|
using System.Net.WebSockets;
|
2017-06-14 01:37:03 +00:00
|
|
|
|
|
|
|
namespace Ooui
|
|
|
|
{
|
|
|
|
public static class UI
|
|
|
|
{
|
2017-06-15 07:40:08 +00:00
|
|
|
static CancellationTokenSource serverCts;
|
|
|
|
|
|
|
|
static readonly Dictionary<string, Func<Element>> publishedPaths =
|
|
|
|
new Dictionary<string, Func<Element>> ();
|
|
|
|
|
|
|
|
static readonly byte[] clientJsBytes;
|
|
|
|
|
|
|
|
static string host = "*";
|
|
|
|
public static string Host {
|
|
|
|
get => host;
|
|
|
|
set {
|
|
|
|
if (!string.IsNullOrWhiteSpace (value) && host != value) {
|
|
|
|
host = value;
|
|
|
|
Restart ();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
static int port = 8080;
|
|
|
|
public static int Port {
|
|
|
|
get => port;
|
|
|
|
set {
|
|
|
|
if (port != value) {
|
|
|
|
port = value;
|
|
|
|
Restart ();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
static UI ()
|
|
|
|
{
|
|
|
|
var asm = typeof(UI).Assembly;
|
|
|
|
// System.Console.WriteLine("ASM = {0}", asm);
|
|
|
|
// foreach (var n in asm.GetManifestResourceNames()) {
|
|
|
|
// System.Console.WriteLine(" {0}", n);
|
|
|
|
// }
|
|
|
|
using (var s = asm.GetManifestResourceStream ("Ooui.Client.js")) {
|
|
|
|
using (var r = new StreamReader (s)) {
|
|
|
|
clientJsBytes = Encoding.UTF8.GetBytes (r.ReadToEnd ());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public static void Publish (string path, Func<Element> elementCtor)
|
|
|
|
{
|
|
|
|
Console.WriteLine ($"PUBLISH {path}");
|
2017-06-16 00:35:20 +00:00
|
|
|
lock (publishedPaths) publishedPaths[path] = elementCtor;
|
2017-06-15 07:40:08 +00:00
|
|
|
Start ();
|
|
|
|
}
|
|
|
|
|
|
|
|
public static void Publish (string path, Element element)
|
|
|
|
{
|
|
|
|
Publish (path, () => element);
|
|
|
|
}
|
|
|
|
|
|
|
|
static void Start ()
|
2017-06-14 01:37:03 +00:00
|
|
|
{
|
2017-06-15 07:40:08 +00:00
|
|
|
if (serverCts != null) return;
|
|
|
|
serverCts = new CancellationTokenSource ();
|
|
|
|
var token = serverCts.Token;
|
|
|
|
var listenerPrefix = $"http://{host}:{port}/";
|
|
|
|
Task.Run (() => RunAsync (listenerPrefix, token), token);
|
2017-06-14 01:37:03 +00:00
|
|
|
}
|
|
|
|
|
2017-06-15 07:40:08 +00:00
|
|
|
static void Stop ()
|
|
|
|
{
|
|
|
|
var scts = serverCts;
|
|
|
|
if (scts == null) return;
|
|
|
|
serverCts = null;
|
|
|
|
|
|
|
|
Console.ForegroundColor = ConsoleColor.Green;
|
|
|
|
Console.WriteLine ($"Stopping...");
|
|
|
|
Console.ResetColor ();
|
2017-06-15 07:58:55 +00:00
|
|
|
|
2017-06-15 07:40:08 +00:00
|
|
|
scts.Cancel ();
|
|
|
|
}
|
|
|
|
|
|
|
|
static void Restart ()
|
|
|
|
{
|
|
|
|
if (serverCts == null) return;
|
|
|
|
Stop ();
|
|
|
|
Start ();
|
|
|
|
}
|
|
|
|
|
|
|
|
static async Task RunAsync (string listenerPrefix, CancellationToken token)
|
|
|
|
{
|
|
|
|
HttpListener listener = null;
|
|
|
|
|
|
|
|
var started = false;
|
|
|
|
while (!started && !token.IsCancellationRequested) {
|
|
|
|
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...");
|
2017-06-16 00:23:07 +00:00
|
|
|
await Task.Delay (wait * 1000).ConfigureAwait (false);
|
2017-06-15 07:40:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
Console.ForegroundColor = ConsoleColor.Green;
|
|
|
|
Console.WriteLine ($"Listening at {listenerPrefix}...");
|
|
|
|
Console.ResetColor ();
|
|
|
|
|
|
|
|
while (!token.IsCancellationRequested) {
|
2017-06-16 00:23:07 +00:00
|
|
|
var listenerContext = await listener.GetContextAsync ().ConfigureAwait (false);
|
2017-06-15 07:40:08 +00:00
|
|
|
if (listenerContext.Request.IsWebSocketRequest) {
|
|
|
|
ProcessWebSocketRequest (listenerContext, token);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
ProcessRequest (listenerContext, token);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
static void ProcessRequest (HttpListenerContext listenerContext, CancellationToken token)
|
|
|
|
{
|
|
|
|
var url = listenerContext.Request.Url;
|
|
|
|
var path = url.LocalPath;
|
|
|
|
|
|
|
|
Console.WriteLine ($"{listenerContext.Request.HttpMethod} {url.LocalPath}");
|
|
|
|
|
|
|
|
var response = listenerContext.Response;
|
|
|
|
|
|
|
|
Func<Element> ctor;
|
|
|
|
|
|
|
|
if (path == "/client.js") {
|
|
|
|
response.ContentLength64 = clientJsBytes.LongLength;
|
|
|
|
response.ContentType = "application/javascript";
|
|
|
|
response.ContentEncoding = Encoding.UTF8;
|
|
|
|
response.AddHeader ("Cache-Control", "public, max-age=3600");
|
|
|
|
using (var s = response.OutputStream) {
|
|
|
|
s.Write (clientJsBytes, 0, clientJsBytes.Length);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
else {
|
2017-06-16 00:35:20 +00:00
|
|
|
var found = false;
|
|
|
|
lock (publishedPaths) found = publishedPaths.TryGetValue (path, out ctor);
|
|
|
|
if (found) {
|
|
|
|
WriteElementHtml (path, response);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
response.StatusCode = 404;
|
|
|
|
response.Close ();
|
|
|
|
}
|
2017-06-15 07:40:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
static void WriteElementHtml (string elementPath, HttpListenerResponse response)
|
|
|
|
{
|
|
|
|
response.StatusCode = 200;
|
|
|
|
response.ContentType = "text/html";
|
|
|
|
response.ContentEncoding = Encoding.UTF8;
|
|
|
|
var html = Encoding.UTF8.GetBytes ($@"<html>
|
|
|
|
<head><title>{elementPath}</title></head>
|
|
|
|
<body>
|
|
|
|
<script>rootElementPath = ""{elementPath}"";</script>
|
|
|
|
<script src=""/client.js""> </script></body>
|
|
|
|
</html>");
|
|
|
|
response.ContentLength64 = html.LongLength;
|
|
|
|
using (var s = response.OutputStream) {
|
|
|
|
s.Write (html, 0, html.Length);
|
|
|
|
}
|
|
|
|
response.Close ();
|
|
|
|
}
|
|
|
|
|
2017-06-16 04:21:38 +00:00
|
|
|
static async void ProcessWebSocketRequest (HttpListenerContext listenerContext, CancellationToken serverToken)
|
2017-06-15 07:40:08 +00:00
|
|
|
{
|
|
|
|
//
|
|
|
|
// Find the element
|
|
|
|
//
|
|
|
|
var url = listenerContext.Request.Url;
|
|
|
|
var path = url.LocalPath;
|
|
|
|
|
|
|
|
Func<Element> ctor;
|
2017-06-16 00:35:20 +00:00
|
|
|
var found = false;
|
|
|
|
lock (publishedPaths) found = publishedPaths.TryGetValue (path, out ctor);
|
|
|
|
if (!found) {
|
2017-06-15 07:40:08 +00:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
|
|
|
//
|
|
|
|
// Connect the web socket
|
|
|
|
//
|
|
|
|
WebSocketContext webSocketContext = null;
|
|
|
|
WebSocket webSocket = null;
|
|
|
|
try {
|
2017-06-16 00:23:07 +00:00
|
|
|
webSocketContext = await listenerContext.AcceptWebSocketAsync (subProtocol: "ooui").ConfigureAwait (false);
|
2017-06-15 07:40:08 +00:00
|
|
|
webSocket = webSocketContext.WebSocket;
|
|
|
|
Console.WriteLine ("WEBSOCKET {0}", listenerContext.Request.Url.LocalPath);
|
|
|
|
}
|
|
|
|
catch (Exception ex) {
|
|
|
|
listenerContext.Response.StatusCode = 500;
|
|
|
|
listenerContext.Response.Close();
|
|
|
|
Error ("Failed to accept WebSocket", ex);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2017-06-15 09:39:19 +00:00
|
|
|
//
|
2017-06-16 04:21:38 +00:00
|
|
|
// Create a new session and let it handle everything from here
|
2017-06-15 07:40:08 +00:00
|
|
|
//
|
|
|
|
try {
|
2017-06-18 08:13:15 +00:00
|
|
|
var session = new Session (webSocket, element, serverToken);
|
|
|
|
await session.RunAsync ().ConfigureAwait (false);
|
2017-06-15 07:40:08 +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) {
|
2017-06-15 09:39:19 +00:00
|
|
|
Error ("Web socket failed", ex);
|
2017-06-15 07:40:08 +00:00
|
|
|
}
|
|
|
|
finally {
|
|
|
|
webSocket?.Dispose ();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
static void Error (string message, Exception ex)
|
2017-06-14 01:37:03 +00:00
|
|
|
{
|
2017-06-15 07:40:08 +00:00
|
|
|
Console.ForegroundColor = ConsoleColor.Red;
|
|
|
|
Console.WriteLine ("{0}: {1}", message, ex);
|
|
|
|
Console.ResetColor ();
|
2017-06-14 01:37:03 +00:00
|
|
|
}
|
2017-06-16 04:21:38 +00:00
|
|
|
|
|
|
|
class Session
|
|
|
|
{
|
|
|
|
readonly WebSocket webSocket;
|
|
|
|
readonly Element element;
|
2017-06-18 08:13:15 +00:00
|
|
|
readonly Action<Message> handleElementMessageSent;
|
|
|
|
|
|
|
|
readonly CancellationTokenSource sessionCts = new CancellationTokenSource ();
|
|
|
|
readonly CancellationTokenSource linkedCts;
|
|
|
|
readonly CancellationToken token;
|
2017-06-16 04:21:38 +00:00
|
|
|
|
2017-06-18 08:13:15 +00:00
|
|
|
readonly HashSet<string> createdIds;
|
|
|
|
readonly List<Message> queuedMessages = new List<Message> ();
|
|
|
|
|
|
|
|
readonly System.Timers.Timer sendThrottle;
|
|
|
|
DateTime lastTransmitTime = DateTime.MinValue;
|
|
|
|
readonly TimeSpan throttleInterval = TimeSpan.FromSeconds (1.0 / 30); // 30 FPS max
|
|
|
|
|
|
|
|
public Session (WebSocket webSocket, Element element, CancellationToken serverToken)
|
2017-06-16 04:21:38 +00:00
|
|
|
{
|
|
|
|
this.webSocket = webSocket;
|
|
|
|
this.element = element;
|
|
|
|
|
|
|
|
//
|
|
|
|
// Create a new session cancellation token that will trigger
|
|
|
|
// automatically if the server shutsdown or the session shutsdown.
|
|
|
|
//
|
2017-06-18 08:13:15 +00:00
|
|
|
linkedCts = CancellationTokenSource.CreateLinkedTokenSource (serverToken, sessionCts.Token);
|
|
|
|
token = linkedCts.Token;
|
2017-06-16 04:21:38 +00:00
|
|
|
|
|
|
|
//
|
|
|
|
// Keep a list of all the elements for which we've transmitted the initial state
|
|
|
|
//
|
2017-06-18 08:13:15 +00:00
|
|
|
createdIds = new HashSet<string> {
|
2017-06-16 04:21:38 +00:00
|
|
|
"window",
|
|
|
|
"document",
|
|
|
|
"document.body",
|
|
|
|
};
|
|
|
|
|
|
|
|
//
|
|
|
|
// Preparse handlers for the element
|
|
|
|
//
|
2017-06-18 08:13:15 +00:00
|
|
|
handleElementMessageSent = QueueMessage;
|
|
|
|
|
|
|
|
//
|
|
|
|
// Create a timer to use as a throttle when sending messages
|
|
|
|
//
|
|
|
|
sendThrottle = new System.Timers.Timer (throttleInterval.TotalMilliseconds);
|
|
|
|
sendThrottle.Elapsed += (s, e) => {
|
2017-06-18 08:17:47 +00:00
|
|
|
// System.Console.WriteLine ("TICK SEND THROTTLE FOR {0}", element);
|
2017-06-18 08:13:15 +00:00
|
|
|
if ((e.SignalTime - lastTransmitTime) >= throttleInterval) {
|
|
|
|
sendThrottle.Enabled = false;
|
|
|
|
lastTransmitTime = e.SignalTime;
|
|
|
|
TransmitQueuedMessages ();
|
2017-06-16 04:21:38 +00:00
|
|
|
}
|
|
|
|
};
|
2017-06-18 08:13:15 +00:00
|
|
|
}
|
2017-06-16 04:21:38 +00:00
|
|
|
|
2017-06-18 08:13:15 +00:00
|
|
|
public async Task RunAsync ()
|
|
|
|
{
|
2017-06-16 04:21:38 +00:00
|
|
|
//
|
|
|
|
// Start watching for changes in the element
|
|
|
|
//
|
2017-06-18 08:13:15 +00:00
|
|
|
element.MessageSent += handleElementMessageSent;
|
2017-06-16 04:21:38 +00:00
|
|
|
|
|
|
|
try {
|
|
|
|
//
|
|
|
|
// Add it to the document body
|
|
|
|
//
|
2017-06-18 08:13:15 +00:00
|
|
|
QueueMessage (Message.Call ("document.body", "appendChild", element));
|
2017-06-16 04:21:38 +00:00
|
|
|
|
|
|
|
//
|
2017-06-18 08:13:15 +00:00
|
|
|
// Start the Read Loop
|
2017-06-16 04:21:38 +00:00
|
|
|
//
|
2017-06-18 08:21:00 +00:00
|
|
|
var receiveBuffer = new byte[64*1024];
|
2017-06-16 04:21:38 +00:00
|
|
|
|
|
|
|
while (webSocket.State == WebSocketState.Open && !token.IsCancellationRequested) {
|
|
|
|
var receiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), token).ConfigureAwait (false);
|
|
|
|
|
|
|
|
if (receiveResult.MessageType == WebSocketMessageType.Close) {
|
|
|
|
await webSocket.CloseAsync (WebSocketCloseStatus.NormalClosure, "", token).ConfigureAwait (false);
|
2017-06-16 04:29:57 +00:00
|
|
|
sessionCts.Cancel ();
|
2017-06-16 04:21:38 +00:00
|
|
|
}
|
|
|
|
else if (receiveResult.MessageType == WebSocketMessageType.Binary) {
|
|
|
|
await webSocket.CloseAsync (WebSocketCloseStatus.InvalidMessageType, "Cannot accept binary frame", token).ConfigureAwait (false);
|
2017-06-16 04:29:57 +00:00
|
|
|
sessionCts.Cancel ();
|
2017-06-16 04:21:38 +00:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
var size = receiveResult.Count;
|
|
|
|
while (!receiveResult.EndOfMessage) {
|
|
|
|
if (size >= receiveBuffer.Length) {
|
|
|
|
await webSocket.CloseAsync (WebSocketCloseStatus.MessageTooBig, "Message too big", token).ConfigureAwait (false);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
receiveResult = await webSocket.ReceiveAsync (new ArraySegment<byte>(receiveBuffer, size, receiveBuffer.Length - size), token).ConfigureAwait (false);
|
|
|
|
size += receiveResult.Count;
|
|
|
|
}
|
|
|
|
var receivedString = Encoding.UTF8.GetString (receiveBuffer, 0, size);
|
|
|
|
|
|
|
|
try {
|
|
|
|
// Console.WriteLine ("RECEIVED: {0}", receivedString);
|
|
|
|
var message = Newtonsoft.Json.JsonConvert.DeserializeObject<Message> (receivedString);
|
|
|
|
element.Receive (message);
|
|
|
|
}
|
|
|
|
catch (Exception ex) {
|
|
|
|
Error ("Failed to process received message", ex);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
finally {
|
2017-06-18 08:13:15 +00:00
|
|
|
element.MessageSent -= handleElementMessageSent;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void QueueStateMessages (EventTarget target)
|
|
|
|
{
|
|
|
|
if (target == null) return;
|
|
|
|
foreach (var m in target.StateMessages) {
|
|
|
|
QueueMessage (m);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void QueueMessage (Message message)
|
|
|
|
{
|
|
|
|
//
|
|
|
|
// Make sure all the referenced objects have been created
|
|
|
|
//
|
|
|
|
if (message.MessageType == MessageType.Create) {
|
|
|
|
createdIds.Add (message.TargetId);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
if (!createdIds.Contains (message.TargetId)) {
|
|
|
|
createdIds.Add (message.TargetId);
|
|
|
|
QueueStateMessages (element.GetElementById (message.TargetId));
|
|
|
|
}
|
|
|
|
if (message.Value is Array a) {
|
|
|
|
for (var i = 0; i < a.Length; i++) {
|
|
|
|
// Console.WriteLine ($"A{i} = {a.GetValue(i)}");
|
|
|
|
if (a.GetValue (i) is EventTarget e && !createdIds.Contains (e.Id)) {
|
|
|
|
createdIds.Add (e.Id);
|
|
|
|
QueueStateMessages (e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
//
|
|
|
|
// Add it to the queue
|
|
|
|
//
|
|
|
|
lock (queuedMessages) queuedMessages.Add (message);
|
|
|
|
sendThrottle.Enabled = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
async void TransmitQueuedMessages ()
|
|
|
|
{
|
|
|
|
try {
|
|
|
|
//
|
|
|
|
// Dequeue as many messages as we can
|
|
|
|
//
|
|
|
|
var messagesToSend = new List<Message> ();
|
|
|
|
lock (queuedMessages) {
|
|
|
|
messagesToSend.AddRange (queuedMessages);
|
|
|
|
queuedMessages.Clear ();
|
|
|
|
}
|
|
|
|
if (messagesToSend.Count == 0)
|
|
|
|
return;
|
|
|
|
|
|
|
|
//
|
|
|
|
// Now actually send this message
|
|
|
|
//
|
|
|
|
var json = Newtonsoft.Json.JsonConvert.SerializeObject (messagesToSend);
|
|
|
|
var outputBuffer = new ArraySegment<byte> (Encoding.UTF8.GetBytes (json));
|
|
|
|
await webSocket.SendAsync (outputBuffer, WebSocketMessageType.Text, true, token).ConfigureAwait (false);
|
|
|
|
}
|
|
|
|
catch (Exception ex) {
|
|
|
|
Error ("Failed to send queued messages, aborting session", ex);
|
|
|
|
element.MessageSent -= handleElementMessageSent;
|
|
|
|
sessionCts.Cancel ();
|
2017-06-16 04:21:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-06-14 01:37:03 +00:00
|
|
|
}
|
|
|
|
}
|