using System; using ln.http.resources.websocket; using ln.http.resources; using ln.http.websocket; using System.Collections.Generic; using ln.json; using ln.logging; using ln.types.rpc; using System.Linq; using System.IO; namespace ln.application { public class ApplicationWebSocket : WebsocketResource { public WebSocket[] CurrentWebSockets { get { lock (currentWebSockets) { return currentWebSockets.ToArray(); } } } HashSet currentWebSockets = new HashSet(); public RPCContainer RPCContainer { get; private set; } public ApplicationWebSocket(Resource container, string name,RPCContainer rpcContainer) :this(container,name) { RPCContainer = rpcContainer; } public ApplicationWebSocket(Resource container,string name) :base(container,name) { Connection += WebSocketInterface_Connection; } void WebSocketInterface_Connection(WebsocketResource webSocketResource, ln.http.websocket.WebSocket webSocket, WSREvent ev) { lock (currentWebSockets) { switch (ev) { case WSREvent.CONNECT: currentWebSockets.Add(webSocket); break; case WSREvent.CLOSE: case WSREvent.ERROR: currentWebSockets.Remove(webSocket); break; } } } public void Broadcast(JSONObject json) { Broadcast(json.ToString()); } public void Broadcast(String text) { foreach (WebSocket webSocket in CurrentWebSockets) { try { webSocket.Send(text); } catch (IOException) { } } } public override void MessageReceived(WebSocketResourceRequestContext requestContext, string textMessage) { try { Logging.Log(LogLevel.DEBUGDETAIL, "ApplicationWebSocket: Received: {0}",textMessage); JSONObject json = (JSONObject)JSONParser.Parse(textMessage); RPCCall rpcCall = json.ToObject(); RPCResult rpcResult = Invoke(rpcCall); string resultText = JSONObject.From(rpcResult).ToString(); Logging.Log(LogLevel.DEBUGDETAIL, "ApplicationWebSocket: Sending: {0}", resultText); requestContext.WebSocket.Send(resultText); } catch (Exception e) { Logging.Log(e); } } public virtual RPCResult Invoke(RPCCall call) { RPCResult result = null; result = RPCContainer.Invoke(call); return result; } } }