Archived
Private
Public Access
1
0

Initial commit

This commit is contained in:
2022-09-04 12:45:01 +02:00
commit f4a01d6a69
11601 changed files with 4206660 additions and 0 deletions

View File

@@ -0,0 +1,41 @@
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WebDesktopBackend.Extentions {
public static class WebSocketExtentions {
public static async Task SendMessage(this WebSocket socket, string message, Encoding encoding = null) {
encoding ??= Encoding.Default;
await socket.SendAsync(new ArraySegment<byte>(encoding.GetBytes(message)), WebSocketMessageType.Text, true, CancellationToken.None);
}
public static async Task<string> RecieveMessage(this WebSocket socket, Encoding encoding = null) {
encoding ??= Encoding.Default;
byte[] buffer = new byte[1024 * 4];
var result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
return encoding.GetString(new ArraySegment<byte>(buffer, 0, result.Count));
}
public static async Task<WebSocket> ConnectAsync(this ClientWebSocket socket, Uri endpoint) {
await socket.ConnectAsync(endpoint, CancellationToken.None);
return socket;
}
public static CancellationTokenSource AddMessageEventHandler(this WebSocket socket, Action<string> handler) {
var source = new CancellationTokenSource();
Task.Run(async () => {
while (!socket.CloseStatus.HasValue) {
string msg = await socket.RecieveMessage();
handler.Invoke(msg);
}
}, source.Token);
return source;
}
}
}