forked from neo-project/neo-modules
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWebSocketClient.cs
83 lines (71 loc) · 2.36 KB
/
WebSocketClient.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
74
75
76
77
78
79
80
81
82
83
using Neo.Json;
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Neo.Plugins
{
internal class WebSocketClient : IDisposable, IEquatable<WebSocketClient>
{
public required WebSocket Socket { get; init; }
public bool IsConnected =>
Socket.State == WebSocketState.Open;
public void Dispose()
{
Socket.Dispose();
GC.SuppressFinalize(this);
}
public async Task SendJsonAsync(JToken message)
{
if (IsConnected)
{
await Socket.SendAsync(
new(Encoding.UTF8.GetBytes(message.ToString())),
WebSocketMessageType.Text,
true,
CancellationToken.None).ConfigureAwait(false);
}
}
public async Task CloseAsync(WebSocketCloseStatus status)
{
switch (Socket.State)
{
case WebSocketState.Connecting:
case WebSocketState.Open:
await Socket.CloseOutputAsync(status, string.Empty, CancellationToken.None).ConfigureAwait(false);
break;
default:
break;
}
}
#region IEquatable
public bool Equals(WebSocketClient other) =>
ReferenceEquals(Socket, other.Socket);
public override int GetHashCode() =>
HashCode.Combine(this, Socket);
public override bool Equals(object obj)
{
if (ReferenceEquals(obj, this))
return true;
if (obj == null)
return false;
if (obj is not WebSocketClient wsObj)
return false;
return Equals(wsObj);
}
public static bool operator ==(WebSocketClient left, WebSocketClient right)
{
if (left as object is null || right as object is null)
return Equals(left, right);
return left.Equals(right);
}
public static bool operator !=(WebSocketClient left, WebSocketClient right)
{
if (left as object is null || right as object is null)
return Equals(left, right) == false;
return left.Equals(right) == false;
}
#endregion
}
}