From a296e2c30f92781e030efe2a09cf118894c10a62 Mon Sep 17 00:00:00 2001 From: Kevin Poirot Date: Fri, 1 Sep 2017 19:29:21 +0200 Subject: [PATCH] Add resource lifecycle events --- WebSocketServer.cs | 69 ++++++++++++++++++++++++++++------------------ 1 file changed, 42 insertions(+), 27 deletions(-) diff --git a/WebSocketServer.cs b/WebSocketServer.cs index 551d4c0..01f9e9a 100644 --- a/WebSocketServer.cs +++ b/WebSocketServer.cs @@ -40,25 +40,6 @@ public WebSocketServer() logLevel = Function.Call(Hash.GET_CONVAR, "websocket_debug", "false") == "true" ? LogLevels.Debug : LogLevels.Info; authorization = Function.Call(Hash.GET_CONVAR, "websocket_authorization", ""); - webSockets = new List(); - EventHandlers["WebSocketServer:broadcast"] += new Action((dynamic message) => - { - lock (webSockets) - { - foreach (var webSocket in webSockets) - { - if (webSocket.IsConnected) - { - webSocket.WriteStringAsync((string) message, CancellationToken.None); - } - else - { - webSockets.Remove(webSocket); - } - } - } - }); - IPAddress listeningHost = IPAddress.Loopback; IPAddress.TryParse(Function.Call(Hash.GET_CONVAR, "websocket_host", "127.0.0.1"), out listeningHost); int listeningPort = Function.Call(Hash.GET_CONVAR_INT, "websocket_port", 80); @@ -92,17 +73,51 @@ public WebSocketServer() TriggerEvent("WebSocketServer:onMessage", msg); }; - try + EventHandlers["onResourceStart"] += new Action((dynamic resourceName) => { - server.Start(); - Tick += server.ListenAsync; + if ((string) resourceName == "WebSocketServer") + { + try + { + server.Start(); + Tick += server.ListenAsync; - Log("Started at " + endpoint.ToString()); - } - catch (Exception e) + Log("Started at " + endpoint.ToString()); + } + catch (Exception e) + { + Log("Can't start server at " + endpoint.ToString() + ": " + e.Message); + } + } + }); + + EventHandlers["onResourceStop"] += new Action((dynamic resourceName) => { - Log("Can't start server at " + endpoint.ToString() + ": " + e.Message); - } + if ((string) resourceName == "WebSocketServer") + { + server.Stop(); + server.Dispose(); + } + }); + + webSockets = new List(); + EventHandlers["WebSocketServer:broadcast"] += new Action((dynamic message) => + { + lock (webSockets) + { + foreach (var webSocket in webSockets) + { + if (webSocket.IsConnected) + { + webSocket.WriteStringAsync((string) message, CancellationToken.None); + } + else + { + webSockets.Remove(webSocket); + } + } + } + }); } private void Log(string message, LogLevels level = LogLevels.Info)