-
Notifications
You must be signed in to change notification settings - Fork 1
/
AsyncWebSocket.cs
73 lines (59 loc) · 2.63 KB
/
AsyncWebSocket.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace crdebug {
public abstract class AsyncWebSocket : IDisposable {
protected abstract WebSocket BaseSocket { get; }
public WebSocketCloseStatus? CloseStatus { get => BaseSocket.CloseStatus; }
public string CloseStatusDescription { get => BaseSocket.CloseStatusDescription; }
public string SubProtocol { get => BaseSocket.SubProtocol; }
public WebSocketState State { get => BaseSocket.State; }
public void Dispose () {
BaseSocket.Dispose();
}
}
public class AsyncClientWebSocket : AsyncWebSocket {
public readonly ClientWebSocket Socket;
private readonly SemaphoreSlim SendSemaphore = new SemaphoreSlim(1);
private readonly SemaphoreSlim RecvSemaphore = new SemaphoreSlim(1);
public ClientWebSocketOptions Options { get => Socket.Options; }
public AsyncClientWebSocket () {
Socket = new ClientWebSocket();
}
protected override WebSocket BaseSocket {
get => Socket;
}
public void Abort () {
Socket.Abort();
}
public Task ConnectAsync (Uri uri, CancellationToken cancellationToken) {
return Socket.ConnectAsync(uri, cancellationToken);
}
public Task CloseAsync (WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) {
return Socket.CloseAsync(closeStatus, statusDescription, cancellationToken);
}
public Task CloseOutputAsync (WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) {
return Socket.CloseOutputAsync(closeStatus, statusDescription, cancellationToken);
}
public async Task<WebSocketReceiveResult> ReceiveAsync (ArraySegment<byte> buffer, CancellationToken cancellationToken) {
await RecvSemaphore.WaitAsync();
try {
return await Socket.ReceiveAsync(buffer, cancellationToken);
} finally {
RecvSemaphore.Release();
}
}
public async Task SendAsync (ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) {
await SendSemaphore.WaitAsync();
try {
await Socket.SendAsync(buffer, messageType, endOfMessage, cancellationToken);
} finally {
SendSemaphore.Release();
}
}
}
}