-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWebSocketExt.cs
More file actions
75 lines (62 loc) · 2.59 KB
/
WebSocketExt.cs
File metadata and controls
75 lines (62 loc) · 2.59 KB
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
using System;
using System.Diagnostics;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
namespace MotionJpegLatencyTest
{
public static class WebSocketExt
{
private static readonly JsonSerializerSettings serializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
public static Task SendDataAsync(this WebSocket socket, ArraySegment<byte> message, CancellationToken cancellation = default)
{
lock (socket)
{
return socket.SendAsync(message, WebSocketMessageType.Binary, true, cancellation);
}
}
public static Task SendTextAsync(this WebSocket socket, string message, CancellationToken cancellation = default)
{
var data = Encoding.UTF8.GetBytes(message);
lock (socket)
{
return socket.SendAsync(new ArraySegment<byte>(data), WebSocketMessageType.Text, true, cancellation);
}
}
public static Task SendJsonAsync(this WebSocket socket, string action, object payload, CancellationToken cancellation = default)
{
var message = new { action, payload };
var data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message, serializerSettings));
lock (socket)
{
return socket.SendAsync(new ArraySegment<byte>(data), WebSocketMessageType.Text, true, cancellation);
}
}
public static Task<JObject> ReceiveJsonAsync(this WebSocket webSocket, CancellationToken cancellation = default, byte[] receiveBuffer = null)
{
Task<WebSocketReceiveResult> task;
lock (webSocket)
{
task = webSocket.ReceiveAsync(
new ArraySegment<byte>(receiveBuffer), cancellation);
}
return task.ContinueWith(t =>
{
var result = t.Result;
Debug.Assert(result.EndOfMessage);
if (result.MessageType == WebSocketMessageType.Close)
return null;
Debug.Assert(result.MessageType == WebSocketMessageType.Text);
var message = Encoding.UTF8.GetString(receiveBuffer, 0, result.Count);
return JObject.Parse(message);
}, cancellation);
}
}
}