-
Notifications
You must be signed in to change notification settings - Fork 0
/
HypeRateClient.cs
175 lines (142 loc) · 5.08 KB
/
HypeRateClient.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
using System.Net.WebSockets;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class HypeRateClient : IDisposable
{
private readonly Uri server_url;
private readonly ClientWebSocket websocket_client;
private readonly Thread heartbeat_thread;
private readonly List<string> send_buffer;
private readonly Thread send_thread;
private readonly Thread receive_thread;
public HypeRateClient(string websocketToken,
int heartbeatIntervallInMilliseconds = 10_000,
string? websocketUrl = null)
{
server_url = new Uri(
string.Format("{0}?token={1}",
websocketUrl ?? "wss://app.hyperate.io/socket/websocket",
websocketToken)
);
websocket_client = new ClientWebSocket();
send_buffer = [];
heartbeat_thread = new Thread(() =>
{
while (true)
{
send_buffer.Add(JsonConvert.SerializeObject(new Heartbeat()));
Thread.Sleep(heartbeatIntervallInMilliseconds);
}
});
send_thread = new Thread(async () =>
{
while (true)
{
if (websocket_client.State != WebSocketState.Open)
{
continue;
}
if (send_buffer.Count == 0)
{
continue;
}
string item_to_send = send_buffer[0];
if (item_to_send == null)
{
continue;
}
send_buffer.RemoveAt(0);
ArraySegment<byte> buffer = new(System.Text.Encoding.UTF8.GetBytes(item_to_send));
await websocket_client.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
Thread.Sleep(1);
}
});
receive_thread = new Thread(async () =>
{
try
{
ArraySegment<byte> input_buffer = new(new byte[1024]);
ArraySegment<byte> temp_input_buffer = new(new byte[1024]);
while (true)
{
if (websocket_client.State != WebSocketState.Open)
{
continue;
}
WebSocketReceiveResult receive_result = await websocket_client.ReceiveAsync(temp_input_buffer, CancellationToken.None);
byte[] result_array = [];
if (input_buffer.Array != null && temp_input_buffer.Array != null)
{
result_array = [.. input_buffer.Array, .. temp_input_buffer.Array];
}
if (receive_result.EndOfMessage)
{
HandleBuffer(result_array, receive_result.Count);
input_buffer = new ArraySegment<byte>(new byte[1024]);
temp_input_buffer = new ArraySegment<byte>(new byte[1024]);
}
else
{
temp_input_buffer = new ArraySegment<byte>(new byte[1024]);
}
}
}
catch (Exception)
{
throw;
}
});
}
public async Task Connect(CancellationToken cancellationToken)
{
await websocket_client.ConnectAsync(server_url, cancellationToken);
send_thread.Start();
receive_thread.Start();
heartbeat_thread.Start();
}
public async void Disconnect(CancellationToken cancellationToken)
{
await websocket_client.CloseAsync(WebSocketCloseStatus.NormalClosure, null, cancellationToken);
}
public static void HandleBuffer(byte[] buffer, int byteCount)
{
if (buffer.Length == 0)
{
return;
}
string utf8_string = System.Text.Encoding.UTF8.GetString(buffer);
if (utf8_string.Length == 0)
{
return;
}
JObject json_object = JObject.Parse(utf8_string);
string? @event = (string?)json_object["event"];
switch (@event)
{
case "hr_update":
IEnumerable<char>? id = string.Join("", ((string?)json_object["topic"])?.Skip(3));
int? heartbeat = (int?)json_object["payload"]["hr"];
Console.WriteLine($"Got new heartbeat for ID {id}: {heartbeat}");
break;
case "phx_reply":
break;
case "phx_close":
break;
default:
Console.WriteLine($"Unknown incomming event {@event}");
break;
}
}
public void JoinChannel(string channelToJoin)
{
send_buffer.Add(JsonConvert.SerializeObject(new JoinChannel(channelToJoin)));
}
public void LeaveChannel(string channelToLeave)
{
send_buffer.Add(JsonConvert.SerializeObject(new LeaveChannel(channelToLeave)));
}
public void Dispose()
{
websocket_client.Dispose();
}
}