- Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathProgram.cs
179 lines (144 loc) · 5.9 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
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
176
177
178
179
usingSystem.Net.WebSockets;
usingSystem.Text;
usingSystem.Collections.Concurrent;
varbuilder=WebApplication.CreateBuilder();
varapp=builder.Build();
app.UseWebSockets();
varcm=newConnectionManager();
intcount=0;
app.Use(async(context,next)=>
{
if(!context.WebSockets.IsWebSocketRequest)
{
awaitnext();
return;
}
varlog=context.RequestServices.GetService<ILoggerFactory>().CreateLogger("app");
varsocket=awaitcontext.WebSockets.AcceptWebSocketAsync();
varsocketId=cm.AddSocket(socket);
awaitReceiveAsync(cm,log,socket,socketId,async(connectionManager,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)inconnectionManager.Other(socketId))
{
socketTasks.Add(s.SendAsync(broadcastBuffer,WebSocketMessageType.Text,true,CancellationToken.None));
log.LogDebug($"Broadcasting to : {sid}");
}
awaitTask.WhenAll(socketTasks);
});
if(socket.State!=WebSocketState.Open)
{
log.LogDebug($"Socket Id {socketId} with status {socket.State}");
}
});
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>
<button type=""button"" id=""close"">Close</button>
<br/>
<ul id=""responses""></ul>
<script>
$(function(){
var url = ""ws://localhost:5000"";
var socket = new WebSocket(url);
var send = $(""#send"");
var close = $(""#close"");
var msg = $(""#msg"");
var responses = $(""#responses"");
socket.onopen = function(e){
responses.append(`<li>Socket opened</li>`);
send.click(function(){
if (socket.readyState !== WebSocket.OPEN){
alert('Socket is closed. Cannot send message.');
return;
}
socket.send(msg.val());
});
};
close.click(function(){
if (socket.readyState !== WebSocket.OPEN){
alert('You cannot close this connection because it is already closed');
return;
}
socket.close();
});
socket.onmessage = function(e){
var response = e.data;
responses.append(`<li>${e.data.trim()}</li>`);
};
socket.onclose = function(e){
responses.append(`<li>Socket closed</li>`);
};
});
</script>
</body>
</html>");
});
app.Run();
asyncTaskReceiveAsync(ConnectionManagercm,ILoggerlog,WebSocketsocket,stringsocketId,Func<ConnectionManager,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.Close)
{
log.LogDebug($"Socket Id {socketId} : Receive closing message.");
varremovalStatus=cm.RemoveSocket(socketId);
log.LogDebug($"Socket Id {socketId} removal status {removalStatus}.");
break;
}
if(result.MessageType!=WebSocketMessageType.Text)
thrownewException("Unexpected Message");
ms.Write(receiveBuffer.Array,receiveBuffer.Offset,result.Count);
}
while(!result.EndOfMessage&&!result.CloseStatus.HasValue);
if(result.MessageType==WebSocketMessageType.Text)
{
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(cm,clientRequest);
}
if(result.CloseStatus.HasValue)
break;
}
}
}
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;
}
publicboolRemoveSocket(stringid)=>_sockets.TryRemove(id,outWebSocketsocket);
publicList<(WebSocketsocket,stringid)>Other(stringid)=>_sockets.Where(x =>x.Key!=id).Select(x =>(socket:x.Value,id:x.Key)).ToList();
}