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 180 181 182 |
using Microsoft.AspNetCore.Hosting; //IWebHostBuilder using Microsoft.AspNetCore.Builder; //IApplicationBuilder using Microsoft.AspNetCore.Http; //WriteAsync using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.AspNetCore; using System; using System.Threading; using System.Net.WebSockets; using System.Text; using System.IO; using System.Collections.Concurrent; using System.Linq; using System.Threading.Tasks; using System.Collections.Generic; namespace WebApplication1 { public class ConnectionManager { ConcurrentDictionary<string, WebSocket> _sockets = new ConcurrentDictionary<string, WebSocket>(); public string AddSocket(WebSocket socket) { var id = Guid.NewGuid().ToString(); if (!_sockets.TryAdd(id, socket)) throw new Exception($"Problem in adding socket with Id {id}"); return id; } public List<(WebSocket socket, string id)> Other(string id) => _sockets.Where(x => x.Key != id).Select(x => (socket: x.Value, id: x.Key)).ToList(); } public class Startup { async Task ReceiveAsync(ILogger log, WebSocket socket, string socketId, Func<string, Task> responseHandlerAsync) { var bufferSize = new byte[4]; //This is especially small just to exercise the code that handles data that is larger than buffer var receiveBuffer = new ArraySegment<byte>(bufferSize); WebSocketReceiveResult result; while (socket.State == WebSocketState.Open) { using (var ms = new MemoryStream()) { do { result = await socket.ReceiveAsync(receiveBuffer, CancellationToken.None); if (result.MessageType != WebSocketMessageType.Text) throw new Exception("Unexpected Message"); ms.Write(receiveBuffer.Array, receiveBuffer.Offset, result.Count); } while (!result.EndOfMessage && !result.CloseStatus.HasValue); ms.Seek(0, SeekOrigin.Begin); string clientRequest = string.Empty; using (var reader = new StreamReader(ms, Encoding.UTF8)) { clientRequest = reader.ReadToEnd(); } log.LogDebug($"Socket Id {socketId} : Receive: {clientRequest}"); await responseHandlerAsync(clientRequest); if (result.CloseStatus.HasValue) break; } } } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger) { //logger.AddConsole((str, level) => !str.Contains("Microsoft.AspNetCore") && level >= LogLevel.Trace); IServiceCollection serviceCollection = new ServiceCollection(); serviceCollection.AddLogging(builder => builder .AddConsole() .AddFilter(level => level >= LogLevel.Information) ); var loggerFactory = serviceCollection.BuildServiceProvider().GetService<ILoggerFactory>(); var log = loggerFactory.CreateLogger(""); app.UseWebSockets(); var cm = new ConnectionManager(); int count = 0; app.Use(async (context, next) => { if (!context.WebSockets.IsWebSocketRequest) { await next(); return; } var socket = await context.WebSockets.AcceptWebSocketAsync(); var socketId = cm.AddSocket(socket); await ReceiveAsync(log, socket, socketId, async (clientRequest) => { var serverReply = Encoding.UTF8.GetBytes($"Echo {++count} {clientRequest}"); var replyBuffer = new ArraySegment<byte>(serverReply); await socket.SendAsync(replyBuffer, WebSocketMessageType.Text, true, CancellationToken.None); var broadcastReply = Encoding.UTF8.GetBytes($"Broadcast {count} {clientRequest}"); var broadcastBuffer = new ArraySegment<byte>(broadcastReply); var socketTasks = new List<Task>(); foreach (var (s, sid) in cm.Other(socketId)) { socketTasks.Add(s.SendAsync(broadcastBuffer, WebSocketMessageType.Text, true, CancellationToken.None)); log.LogDebug($"Broadcasting to : {sid}"); } await Task.WhenAll(socketTasks); }); }); app.Run(async context => { context.Response.Headers.Add("content-type", "text/html"); await context.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 = ""wss://localhost:44323/""; 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('<BR/>'); responses.append(response.trim()); }; }); </script> </body> </html>"); }); } } public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseEnvironment("Development"); } } |
출력 :
Echo 1 hello world
Echo 2 hello world
Echo 3 hello world