ln.application/ApplicationWebSocket.cs

100 lines
2.2 KiB
C#
Raw Normal View History

2019-08-20 08:33:38 +02:00
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;
namespace ln.application
{
public class ApplicationWebSocket : WebsocketResource
{
public WebSocket[] CurrentWebSockets
{
get
{
lock (currentWebSockets)
{
return currentWebSockets.ToArray();
}
}
}
HashSet<WebSocket> currentWebSockets = new HashSet<WebSocket>();
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:
currentWebSockets.Remove(webSocket);
break;
}
}
}
public void Broadcast(JSONObject json)
{
Broadcast(json.ToString());
}
public void Broadcast(String text)
{
foreach (WebSocket webSocket in CurrentWebSockets)
{
webSocket.Send(text);
}
}
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<RPCCall>();
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;
}
}
}