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 |
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; namespace WebApplication1 { public class Startup { public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger) { logger.AddConsole((str, level) => { //filter out framework log messages return !str.Contains("Microsoft.AspNetCore") && level >= LogLevel.Trace; }); var log = logger.CreateLogger(""); app.UseWebSockets(); app.Use(async (context, next) => { if (!context.WebSockets.IsWebSocketRequest) { // Not a web socket request await next(); return; } var socket = await context.WebSockets.AcceptWebSocketAsync(); var bufferSize = new byte[4]; var receiveBuffer = new ArraySegment<byte>(bufferSize); WebSocketReceiveResult result; while (socket.State == WebSocketState.Open) { using (var ms = new MemoryStream()) { int count = 0; 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); receiveBuffer = new ArraySegment<byte>(bufferSize); log.LogDebug($"Reading incoming data with buffer(size {bufferSize.Length}) {++count} times"); } while (!result.EndOfMessage && !result.CloseStatus.HasValue); ms.Seek(0, SeekOrigin.Begin); string clientRequest = string.Empty; using (var reader = new StreamReader(ms, Encoding.UTF8)) { clientRequest = await reader.ReadToEndAsync(); } log.LogDebug($"Receive: {clientRequest}"); var serverReply = Encoding.UTF8.GetBytes("Echo " + clientRequest); var replyBuffer = new ArraySegment<byte>(serverReply); await socket.SendAsync(replyBuffer, WebSocketMessageType.Text, true, CancellationToken.None); if (result.CloseStatus.HasValue) break; } } }); 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</h1> <input type=""text"" length=""50"" id=""msg"" value=""hello world""/> <button type=""button"" id=""send"">Send</button> <br/> <script> $(function(){ var url = ""wss://localhost:44323/""; var socket = new WebSocket(url); var send = $(""#send""); var msg = $(""#msg""); socket.onopen = function(e){ send.click(function(){ socket.send(msg.val()); }); }; socket.onmessage = function(e){ var response = e.data; alert(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"); } } |
결과 : ??