tesses-rpc/Tesses.SystemNetWebSocketsRPC/Class1.cs

108 lines
3.7 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.IO;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Tesses.RPC
{
public class WebSocketClientMessageHandler : MessageHandler
{
ClientWebSocket client;
string url;
Action start;
public WebSocketClientMessageHandler(string url,Action start)
{
client=new ClientWebSocket();
this.start =start;
this.url = url;
}
public void Connect()
{
Task.Run(ConnectAsync).Wait();
}
public async Task ConnectAsync()
{
await ConnectAsync(default);
}
public async Task ConnectAsync(CancellationToken token)
{
await client.ConnectAsync(new Uri(url),token);
Thread t2 = new Thread(()=>{
start?.Invoke();
});
t2.Start();
Thread t = new Thread(async()=>{
try{
var buffer=new ArraySegment<byte>(new byte[2048]);
while(!token.IsCancellationRequested)
{
WebSocketReceiveResult result;
var ms=new MemoryStream();
do{
result = await client.ReceiveAsync(buffer,token);
ms.Write(buffer.Array,buffer.Offset,buffer.Count);
} while(!result.EndOfMessage);
ms.Position=0;
string text=Encoding.UTF8.GetString(ms.ToArray());
if(!string.IsNullOrWhiteSpace(text))
{
this.OnMessageReceived(text);
}
if(result.MessageType == WebSocketMessageType.Close)
break;
}
}catch(Exception ex)
{
_=ex;
}
});
t.Start();
}
public override void SendMessage(string msg)
{
Task.Run(async ()=>await SendMessageAsync(msg)).Wait();
}
public async Task SendMessageAsync(string msg,CancellationToken token=default)
{
MemoryStream strm = new MemoryStream(Encoding.UTF8.GetBytes(msg));
strm.Position = 0;
int read = 0;
byte[] buffer = new byte[1024];
do{
read=strm.Read(buffer,0,buffer.Length);
ArraySegment<byte> seg = new ArraySegment<byte>(buffer,0,read);
await client.SendAsync(seg,WebSocketMessageType.Text,strm.Position == strm.Length,token);
}while(read!=0);
}
}
}