-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebSocketController.cs
77 lines (66 loc) · 2.69 KB
/
WebSocketController.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
using System.Text;
using System.Net.WebSockets;
using Microsoft.AspNetCore.Mvc;
namespace CoDraw;
public class WebSocketController : Controller
{
private readonly IWebSocketManager _webSocketManager;
public WebSocketController(IWebSocketManager webSocketManager)
{
_webSocketManager = webSocketManager;
}
[HttpGet("/wschat")]
public async Task Get()
{
// read uuid from url
var uuidString = HttpContext.Request.Query["uuid"];
Console.WriteLine("Opening websocket for UUID: " + uuidString);
if (HttpContext.WebSockets.IsWebSocketRequest)
{
using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
_webSocketManager.AddSocket(webSocket, uuidString); // Add the new WebSocket to the list.
Console.WriteLine("WebSocket connection established, current connections: " + _webSocketManager.GetAllSockets().Count);
await Echo(webSocket, uuidString);
_webSocketManager.RemoveSocket(webSocket); // Remove the WebSocket when it's done
}
else
{
HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
}
}
public async Task Echo(WebSocket webSocket, String uuid)
{
var buffer = new byte[256];
WebSocketReceiveResult receiveResult;
do
{
receiveResult = await webSocket.ReceiveAsync(
new ArraySegment<byte>(buffer), CancellationToken.None);
var receivedString = Encoding.UTF8.GetString(buffer, 0, receiveResult.Count);
Console.WriteLine($"Received: {receivedString}");
var sendBuffer = Encoding.UTF8.GetBytes(receivedString);
if (receiveResult.MessageType == WebSocketMessageType.Close)
{
Console.WriteLine("Received close message");
continue;
}
foreach (var socket in _webSocketManager.GetAllSockets(uuid))
{
if (socket.State == WebSocketState.Open)
{
await socket.SendAsync(
new ArraySegment<byte>(sendBuffer, 0, sendBuffer.Length),
receiveResult.MessageType,
receiveResult.EndOfMessage,
CancellationToken.None);
}
}
}
while (!receiveResult.CloseStatus.HasValue);
Console.WriteLine("Connection closed");
await webSocket.CloseAsync(
receiveResult.CloseStatus.Value,
receiveResult.CloseStatusDescription,
CancellationToken.None);
}
}