- Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathProgram.cs
141 lines (112 loc) · 4.59 KB
/
Program.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
usingSystem.Net.WebSockets;
usingSystem.Text;
usingSystem.Collections.Concurrent;
varbuilder=WebApplication.CreateBuilder();
builder.Services.AddSingleton<ConnectionManager>();
asyncTaskReceiveAsync(ILoggerlog,WebSocketsocket,stringsocketId,Func<string,Task>responseHandlerAsync)
{
varbufferSize=newbyte[4];//This is especially small just to exercise the code that handles data that is larger than buffer
varreceiveBuffer=newArraySegment<byte>(bufferSize);
WebSocketReceiveResultresult;
while(socket.State==WebSocketState.Open)
{
using(varms=newMemoryStream())
{
do
{
result=awaitsocket.ReceiveAsync(receiveBuffer,CancellationToken.None);
if(result.MessageType!=WebSocketMessageType.Text)
thrownewException("Unexpected Message");
ms.Write(receiveBuffer.Array,receiveBuffer.Offset,result.Count);
}
while(!result.EndOfMessage&&!result.CloseStatus.HasValue);
ms.Seek(0,SeekOrigin.Begin);
stringclientRequest=string.Empty;
using(varreader=newStreamReader(ms,Encoding.UTF8))
{
clientRequest=reader.ReadToEnd();
}
log.LogDebug($"Socket Id {socketId} : Receive: {clientRequest}");
awaitresponseHandlerAsync(clientRequest);
if(result.CloseStatus.HasValue)
break;
}
}
}
varapp=builder.Build();
app.UseWebSockets();
intcount=0;
app.Use(async(context,next)=>
{
varlog=context.RequestServices.GetService<ILoggerFactory>().CreateLogger("app");
varcm=context.RequestServices.GetService<ConnectionManager>();
if(!context.WebSockets.IsWebSocketRequest)
{
awaitnext(context);
return;
}
varsocket=awaitcontext.WebSockets.AcceptWebSocketAsync();
varsocketId=cm.AddSocket(socket);
awaitReceiveAsync(log,socket,socketId,async(clientRequest)=>
{
varserverReply=Encoding.UTF8.GetBytes($"Echo {++count}{clientRequest}");
varreplyBuffer=newArraySegment<byte>(serverReply);
awaitsocket.SendAsync(replyBuffer,WebSocketMessageType.Text,true,CancellationToken.None);
varbroadcastReply=Encoding.UTF8.GetBytes($"Broadcast {count}{clientRequest}");
varbroadcastBuffer=newArraySegment<byte>(broadcastReply);
varsocketTasks=newList<Task>();
foreach(var(s,sid)incm.Other(socketId))
{
socketTasks.Add(s.SendAsync(broadcastBuffer,WebSocketMessageType.Text,true,CancellationToken.None));
log.LogDebug($"Broadcasting to : {sid}");
}
awaitTask.WhenAll(socketTasks);
});
});
app.Run(async context =>
{
context.Response.Headers.Append("content-type","text/html");
awaitcontext.Response.WriteAsync(@"
<html>
<head>
<script src=""https://code.jquery.com/jquery-3.2.1.min.js"" integrity=""sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="" crossorigin=""anonymous""></script>
</head>
<body>
<h1>Web Socket (please open this page at 2 tabs at least)</h1>
<input type=""text"" length=""50"" id=""msg"" value=""hello world""/> <button type=""button"" id=""send"">Send</button>
<br/>
<ul id=""responses""></ul>
<script>
$(function(){
var url = ""ws://localhost:5000"";
var socket = new WebSocket(url);
var send = $(""#send"");
var msg = $(""#msg"");
var responses = $(""#responses"");
socket.onopen = function(e){
send.click(function(){
socket.send(msg.val());
});
};
socket.onmessage = function(e){
var response = e.data;
responses.append(`<li>${e.data.trim()}</li>`);
};
});
</script>
</body>
</html>");
});
app.Run();
publicclassConnectionManager
{
ConcurrentDictionary<string,WebSocket>_sockets=newConcurrentDictionary<string,WebSocket>();
publicstringAddSocket(WebSocketsocket)
{
varid=Guid.NewGuid().ToString();
if(!_sockets.TryAdd(id,socket))
thrownewException($"Problem in adding socket with Id {id}");
returnid;
}
publicList<(WebSocketsocket,stringid)>Other(stringid)=>_sockets.Where(x =>x.Key!=id).Select(x =>(socket:x.Value,id:x.Key)).ToList();
}