visual studio 2017 net core 설치
1. 사이트 https://visualstudio.microsoft.com/ko/downloads/ 2. 다운로드 및 설치 3. 설치중 4. Net core 프로그램 선택 후 설치 5. 설치중
1. 사이트 https://visualstudio.microsoft.com/ko/downloads/ 2. 다운로드 및 설치 3. 설치중 4. Net core 프로그램 선택 후 설치 5. 설치중
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 |
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 Microsoft.Extensions.Configuration; using System.Collections.Generic; using Microsoft.AspNetCore.WebUtilities; //QueryHelpers namespace WebApplication1 { public class Startup { public Startup(IHostingEnvironment env, ILoggerFactory logger) { //These are two services available at constructor } public void ConfigureServices(IServiceCollection services) { //This is the only service available at ConfigureServices } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger, IConfiguration configuration) { app.Run(async context => { var queryString = QueryHelpers.ParseQuery(context.Request.QueryString.ToString()); var output = ""; foreach (var qs in queryString) { output += qs.Key + " = " + qs.Value + "<br/>"; } await context.Response.WriteAsync($@"<html> <body> <h1>Parsing Raw Query String</h1> <ul> <li><a href=""?name=anne"">?name=anne</a></li> <li><a href=""?name=anne&name=mishkind"">?name=anne&name=mishkind</a></li> <li><a href=""?age=25&smart=true"">?age=25&smart=true</a></li> <li><a href=""?country=zambia&country=senegal&country="">?country=zambia&country=senegal&country=</a></li> <li><a href=""?"">?</a></li> <br /><br /> <strong>Query String</strong><br/> {output} </ul> </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"); } } |
결과 : Parsing Raw Query String •?name=anne •?name=anne&name=mishkind •?age=25&smart=true •?country=zambia&country=senegal&country= •? Query String name = anne,mishkind
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 |
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 Microsoft.Extensions.Configuration; using System.Collections.Generic; using Microsoft.AspNetCore.WebUtilities; //QueryHelpers namespace WebApplication1 { public class Startup { public Startup(IHostingEnvironment env, ILoggerFactory logger) { //These are two services available at constructor } public void ConfigureServices(IServiceCollection services) { //This is the only service available at ConfigureServices } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger, IConfiguration configuration) { var arguments = new Dictionary<string, string>() { {"greetings", "hello-world"}, {"origin", "cairo"} }; var path = QueryHelpers.AddQueryString("/greet", arguments); app.Run(context => { return context.Response.WriteAsync($"{path}"); }); } } 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"); } } |
결과 : /greet?greetings=hello-world&origin=cairo
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 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 |
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 socket, string nickname)> _sockets = new ConcurrentDictionary<string, (WebSocket, string)>(); public string AddSocket(WebSocket socket) { var id = Guid.NewGuid().ToString(); if (!_sockets.TryAdd(id, (socket, string.Empty))) throw new Exception($"Problem in adding socket with Id {id}"); return id; } public bool SetNickName(string id, string nickname) { if (_sockets.TryGetValue(id, out var x)) { _sockets[id] = (x.socket, nickname); return true; } else return false; } public (bool, string) GetNickNameById(string id) { if (_sockets.TryGetValue(id, out var x)) return (true, x.nickname); else return (false, null); } public (bool, WebSocket socket) GetByNick(string nickname) { var found = _sockets.Where(x => x.Value.nickname.Equals(nickname, StringComparison.CurrentCultureIgnoreCase)).Take(1).ToList(); if (found.Count == 0) return (false, null); else return (true, found[0].Value.socket); } public bool RemoveSocket(string id) => _sockets.TryRemove(id, out (WebSocket, string) _); public List<(WebSocket socket, string id, string nickname)> Other(string id) => _sockets.Where(x => x.Key != id) .Select(x => (x.Value.socket, x.Key, x.Value.nickname)) .ToList(); } public enum CommandType { List, Send, Nick, Quit } public class Command { public CommandType Type { get; set; } public (string, string, string) Data { get; set; } } public class CommandHandler { public (bool, Command) Parse(string cmd) { try { if (cmd.StartsWith("#")) { var segment = cmd.Split(new[] { ' ' }); if (segment.Length > 0) { switch (segment[0]) { case "#list": return (true, new Command { Type = CommandType.List, Data = ("", "", "") }); case "#quit": return (true, new Command { Type = CommandType.Quit, Data = ("", "", "") }); case "#nick": return (true, new Command { Type = CommandType.Nick, Data = (segment[1], "", "") }); case "#talk": return (true, new Command { Type = CommandType.Send, Data = (segment[1], string.Join(" ", segment.Skip(2)), "") }); default: return (false, null); } } } return (false, null); } catch { return (false, null); } } } public class Startup { async Task ReceiveAsync(ConnectionManager cm, ILogger log, WebSocket socket, string socketId, Func<ConnectionManager, 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.Close) { log.LogDebug($"Socket Id {socketId} : Receive closing message."); var removalStatus = cm.RemoveSocket(socketId); log.LogDebug($"Socket Id {socketId} removal status {removalStatus}."); break; } if (result.MessageType != WebSocketMessageType.Text) throw new Exception("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); string clientRequest = string.Empty; using (var reader = new StreamReader(ms, Encoding.UTF8)) { clientRequest = reader.ReadToEnd(); } log.LogDebug($"Socket Id {socketId} : Receive: {clientRequest}"); await responseHandlerAsync(cm, clientRequest); } if (result.CloseStatus.HasValue) break; } } } public ArraySegment<byte> Reply(string content) => new ArraySegment<byte>(Encoding.UTF8.GetBytes(content)); public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger) { // logger.AddConsole((str, level) => !str.Contains("Microsoft.AspNetCore") && level >= LogLevel.Trace); var log = logger.CreateLogger(""); app.UseWebSockets(); var cm = new ConnectionManager(); app.Use(async (context, next) => { if (!context.WebSockets.IsWebSocketRequest) { await next(); return; } var socket = await context.WebSockets.AcceptWebSocketAsync(); var socketId = cm.AddSocket(socket); var cmdHandler = new CommandHandler(); await ReceiveAsync(cm, log, socket, socketId, async (connectionManager, clientRequest) => { var (isOK, cmd) = cmdHandler.Parse(clientRequest); if (isOK) { switch (cmd.Type) { case CommandType.List: { var others = connectionManager.Other(socketId).Select(x => string.IsNullOrWhiteSpace(x.nickname) ? "NoNick" : x.nickname).ToList(); if (others.Count > 0) await socket.SendAsync(Reply(string.Join(",", others)), WebSocketMessageType.Text, true, CancellationToken.None); else await socket.SendAsync(Reply("No other user on this channel"), WebSocketMessageType.Text, true, CancellationToken.None); break; } case CommandType.Nick: { var isOk = connectionManager.SetNickName(socketId, cmd.Data.Item1); if (isOK) await socket.SendAsync(Reply($"Nickname now {cmd.Data.Item1}"), WebSocketMessageType.Text, true, CancellationToken.None); else await socket.SendAsync(Reply($"#nick fails"), WebSocketMessageType.Text, true, CancellationToken.None); break; } case CommandType.Send: { var (isFound, sck) = connectionManager.GetByNick(cmd.Data.Item1); if (isFound) { var (isOk, sender) = connectionManager.GetNickNameById(socketId); if (isOK) await sck.SendAsync(Reply($"From {sender}: {cmd.Data.Item2}"), WebSocketMessageType.Text, true, CancellationToken.None); else await sck.SendAsync(Reply($"From Unknown: {cmd.Data.Item2}"), WebSocketMessageType.Text, true, CancellationToken.None); await socket.SendAsync(Reply($"Message sent to {cmd.Data.Item1}"), WebSocketMessageType.Text, true, CancellationToken.None); } else await socket.SendAsync(Reply($"{cmd.Data.Item1} not found"), WebSocketMessageType.Text, true, CancellationToken.None); break; } case CommandType.Quit: { connectionManager.RemoveSocket(socketId); await socket.SendAsync(Reply("Quitting chat"), WebSocketMessageType.Text, true, CancellationToken.None); await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); break; } default: { await socket.SendAsync(Reply("Command not understood"), WebSocketMessageType.Text, true, CancellationToken.None); break; } } } else await socket.SendAsync(Reply("Command not understood"), WebSocketMessageType.Text, true, CancellationToken.None); }); if (socket.State != WebSocketState.Open) log.LogDebug($"Socket Id {socketId} with status {socket.State}"); }); 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> <p>Commands<p> <ul> <li>#list</li> <li>#nick <i>nickname</i></li> <li>#talk <i>nickname</i> <i>text</i></li> <li>#quit</li> </ul> <input type=""text"" length=""50"" id=""msg"" value=""#nick anne""/> <button type=""button"" id=""send"">Send</button> <button type=""button"" id=""close"">Close</button> <br/> <ul id=""responses""></ul> <script> $(function(){ var url = ""wss://localhost:44323/""; 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('<BR/>'); responses.append(response.trim()); //alert(response.trim()); }; socket.onclose = function(e){ responses.append('<li>Socket closed</li>'); }; }); </script> </body> </html>"); }); } } public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseEnvironment("Development"); } } |
결과 : Web Socket (please open this page at 2 tabs at least) Commands •#list •#nick nickname •#talk nickname text •#quit [ ] Send Close •Socket opened Nickname now nickname2 Message sent to nickname1 From nickname1: text Message sent to nickname nickname1,nickname Message sent to nickname1 •Socket closed
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
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"); } } |
결과 : ??
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
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 |
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 Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Rewrite; //UseRewriter using System; using System.Net; using Microsoft.Net.Http.Headers; using System.IO; namespace WebApplication1 { public class ExtensionRedirection : IRule { readonly string _extension; readonly PathString _newPath; public ExtensionRedirection(string extension, string newPath) { _extension = extension; _newPath = new PathString(newPath); } public void ApplyRule(RewriteContext context) { var request = context.HttpContext.Request; // Because we're redirecting back to the same app, stop processing if the request has already been redirected // This is to prevent crazy loop. Try it, comment below code and you are going to crash. if (request.Path.StartsWithSegments(new PathString(_newPath))) { return; } if (request.Path.Value.EndsWith(_extension, StringComparison.OrdinalIgnoreCase)) { var response = context.HttpContext.Response; response.StatusCode = StatusCodes.Status301MovedPermanently; context.Result = RuleResult.EndResponse; response.Headers[HeaderNames.Location] = _newPath + request.Path + request.QueryString; } } } public class Startup { public Startup(IHostingEnvironment env, ILoggerFactory logger) { } public void ConfigureServices(IServiceCollection services) { //This is the only service available at ConfigureServices services.AddRouting(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger) { var options = new RewriteOptions() .Add(new ExtensionRedirection(".png", "/images/png")) .Add(new ExtensionRedirection(".jpg", "/images/jpeg")); app.UseRewriter(options); app.UseStaticFiles(); var routes = new RouteBuilder(app); routes.MapGet("", async context => { context.Response.Headers.Add("content-type", "text/html"); var path = context.Request.Query["Path"]; var ext = context.Request.Query["Ext"]; await context.Response.WriteAsync($"<h1>Extension Based Redirection</h1><img src=\"ryan-wong-25025.jpg\" /> <br/> <img src=\"Acorn_PNG744.png\" />"); }); app.UseRouter(routes.Build()); } } 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"); } } |
결과 : Extension Based Redirection [이미지] //생략 [이미지] //생략
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 |
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 Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Rewrite; //UseRewriter using System.Net; namespace WebApplication1 { public class Startup { public Startup(IHostingEnvironment env, ILoggerFactory logger) { } public void ConfigureServices(IServiceCollection services) { //This is the only service available at ConfigureServices services.AddRouting(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger) { var options = new RewriteOptions() .AddRedirect("([/_0-9a-z-]+)+(.*)$", "/?path=$1&ext=$2"); //redirect any path that ends with .html //.AddRewrite("([/_0-9a-z-]+)+(.*)$", "/?path=$1&ext=$2", skipRemainingRules: false); //redirect any path that ends with .html //.AddRedirect("([/_0-9a-z-]+)+(.*)$", "/?path=$1&ext=$2", (int)HttpStatusCode.MovedPermanently); //redirect any path that ends with .html app.UseRewriter(options); var routes = new RouteBuilder(app); routes.MapGet("", (context) => { context.Response.Headers.Add("content-type", "text/html"); var path = context.Request.Query["Path"]; var ext = context.Request.Query["Ext"]; return context.Response.WriteAsync($@"Always display this page when path ends with an extension (e.g. .html or .aspx) and capture the their values. For example <a href=""/hello-world.html"">/hello-world.html</a> or <a href=""/welcome/everybody/inthis/train.aspx"">/welcome/everybody/inthis/train.aspx</a>. <br/><br/> Query String ""path"" = {path}<br/> Query String ""ext"" = {ext}<br/> "); }); app.UseRouter(routes.Build()); } } 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"); } } |
결과 : Always display this page when path ends with an extension (e.g. .html or .aspx) and capture the their values.For example /hello-world.html or /welcome/everybody/inthis/train.aspx. Query String “path” = welcome/everybody/inthis/train Query String “ext” = .aspx
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 |
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 Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Rewrite; //UseRewriter namespace WebApplication1 { public class Startup { public Startup(IHostingEnvironment env, ILoggerFactory logger) { } public void ConfigureServices(IServiceCollection services) { //This is the only service available at ConfigureServices services.AddRouting(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger) { var options = new RewriteOptions() .AddRedirect("/$", "/"); //redirect when path ends with / app.UseRewriter(options); var routes = new RouteBuilder(app); routes.MapGet("", (context) => { context.Response.Headers.Add("content-type", "text/html"); return context.Response.WriteAsync($"Always display this page when path ends with / e.g. <a href=\"/hello-world/\">/hello-world/</a> or <a href=\"/welcome/everybody/inthis/train/\">/welcome/everybody/inthis/train/</a>."); }); app.UseRouter(routes.Build()); } } 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"); } } |
결과 : Always display this page when path ends with / e.g. /hello-world/ or /welcome/everybody/inthis/train/.