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 |
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; namespace WebApplication1 { public class Startup { public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger) { 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[1024 * 4]; var receiveBuffer = new ArraySegment<byte>(bufferSize); var result = await socket.ReceiveAsync(receiveBuffer, CancellationToken.None); while (!result.CloseStatus.HasValue) { if (result.MessageType == WebSocketMessageType.Text) { var clientRequest = Encoding.UTF8.GetString(receiveBuffer.Array, receiveBuffer.Offset, receiveBuffer.Count); var serverReply = Encoding.UTF8.GetBytes("Echo " + clientRequest); var replyBuffer = new ArraySegment<byte>(serverReply); await socket.SendAsync(replyBuffer, WebSocketMessageType.Text, true, CancellationToken.None); receiveBuffer = new ArraySegment<byte>(bufferSize); result = await socket.ReceiveAsync(receiveBuffer, CancellationToken.None); } } }); 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"); } } |
결과 :
Echo hello world