tesses-rpc/Tesses.WebServer.WebSocketRPC/Class1.cs

68 lines
2.0 KiB
C#
Raw Permalink Normal View History

2022-12-12 17:24:00 +00:00
/*
Tesses.RPC A simple RPC library for .NET
Copyright (C) 2023 Mike Nolan
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using Tesses.WebServer;
using Tesses.WebServer.WebSocket;
namespace Tesses.RPC
{
public sealed class RPCServer : EasyWebSocketServer
{
private class _MH : MessageHandler
{
RPCServer svr;
public _MH(RPCServer svr)
{
this.svr=svr;
}
public override void SendMessage(string msg)
{
svr.SendMessage(WebSocketMessage.Create(msg));
}
}
_MH mh;
Action<MessageHandler> mhcb;
public RPCServer(Action<MessageHandler> start)
{
mh=new _MH(this);
this.mhcb = start;
}
public override async Task OnConnectionStarted(CancellationToken token)
{
Task.Factory.StartNew(()=>mhcb?.Invoke(mh)).Wait(0);
await Task.FromResult(true);
}
public override async Task OnReceiveMessage(WebSocketMessage msg)
{
await Task.Run(()=>mh.OnMessageReceived(msg.Text));
}
}
}