|
| 1 | +using System; |
| 2 | +using System.Linq; |
| 3 | +using System.Threading.Tasks; |
| 4 | +using Microsoft.AspNetCore.Builder; |
| 5 | +using Microsoft.AspNetCore.Hosting; |
| 6 | +using Microsoft.AspNetCore.Http; |
| 7 | +using Microsoft.Extensions.DependencyInjection; |
| 8 | +using Microsoft.Extensions.Logging; |
| 9 | +using System.Net.WebSockets; |
| 10 | +using System.Threading; |
| 11 | +using System.Text; |
| 12 | +using System.Collections.Concurrent; |
| 13 | + |
| 14 | +namespace AspNetCoreWebSocket |
| 15 | +{ |
| 16 | +public class Startup |
| 17 | +{ |
| 18 | +// This method gets called by the runtime. Use this method to add services to the container. |
| 19 | +// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 |
| 20 | +public void ConfigureServices(IServiceCollection services) |
| 21 | +{ |
| 22 | +} |
| 23 | + |
| 24 | +// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. |
| 25 | +public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) |
| 26 | +{ |
| 27 | +loggerFactory.AddConsole(); |
| 28 | + |
| 29 | +if (env.IsDevelopment()) |
| 30 | +{ |
| 31 | +app.UseDeveloperExceptionPage(); |
| 32 | +} |
| 33 | + |
| 34 | +var options = new WebSocketOptions { ReceiveBufferSize = 4096 }; |
| 35 | +app.UseWebSockets(options); |
| 36 | + |
| 37 | +/* |
| 38 | + * This form is OK (it seems normal than examples below) |
| 39 | + * I used Map method to show 3 examples in 1 file. |
| 40 | + * http://localhost:5000/ |
| 41 | + * |
| 42 | +app.Use(async (context, next) => |
| 43 | +{ |
| 44 | +if (context.WebSockets.IsWebSocketRequest) |
| 45 | +{ |
| 46 | +// process... |
| 47 | +} |
| 48 | +else |
| 49 | +{ |
| 50 | +await next(); |
| 51 | +} |
| 52 | +}); |
| 53 | +*/ |
| 54 | + |
| 55 | +/* |
| 56 | + * Bad example |
| 57 | + * Echoes message only once (lose connection after echo) |
| 58 | + * http://localhost:5000/Once |
| 59 | + */ |
| 60 | +app.Map("/Bad", once => |
| 61 | +{ |
| 62 | +once.Use(async (context, next) => |
| 63 | +{ |
| 64 | +if (context.WebSockets.IsWebSocketRequest) |
| 65 | +{ |
| 66 | +// WebSocket request |
| 67 | +using (var socket = await context.WebSockets.AcceptWebSocketAsync()) |
| 68 | +{ |
| 69 | +if (socket?.State == WebSocketState.Open) |
| 70 | +{ |
| 71 | +// Handle the socket |
| 72 | +var receiveToken = CancellationToken.None; |
| 73 | +var receiveBuffer = new ArraySegment<byte>(new byte[4096]); |
| 74 | + |
| 75 | +var received = await socket.ReceiveAsync(receiveBuffer, receiveToken); |
| 76 | +if (received.MessageType == WebSocketMessageType.Text) |
| 77 | +{ |
| 78 | +var text = Encoding.UTF8.GetString(receiveBuffer.Array, receiveBuffer.Offset, receiveBuffer.Count); |
| 79 | + |
| 80 | +// echo |
| 81 | +var sendingToken = CancellationToken.None; |
| 82 | +var sendingData = Encoding.UTF8.GetBytes(text); |
| 83 | +var sendingBuffer = new ArraySegment<byte>(sendingData); |
| 84 | +await socket.SendAsync(sendingBuffer, WebSocketMessageType.Text, true, sendingToken); |
| 85 | +} |
| 86 | +} |
| 87 | +} |
| 88 | +} |
| 89 | +else |
| 90 | +{ |
| 91 | +await next(); |
| 92 | +} |
| 93 | +}); |
| 94 | +}); |
| 95 | + |
| 96 | +/* |
| 97 | + * Single example |
| 98 | + * Echoes message until close connection |
| 99 | + * http://localhost:5000/Single |
| 100 | + */ |
| 101 | +app.Map("/Single", once => |
| 102 | +{ |
| 103 | +once.Use(async (context, next) => |
| 104 | +{ |
| 105 | +if (context.WebSockets.IsWebSocketRequest) |
| 106 | +{ |
| 107 | +// WebSocket request |
| 108 | +using (var socket = await context.WebSockets.AcceptWebSocketAsync()) |
| 109 | +{ |
| 110 | +if (socket?.State == WebSocketState.Open) |
| 111 | +{ |
| 112 | +// Handle the socket |
| 113 | +var receiveToken = CancellationToken.None; |
| 114 | +var receiveBuffer = new ArraySegment<byte>(new byte[4096]); |
| 115 | + |
| 116 | +var received = await socket.ReceiveAsync(receiveBuffer, receiveToken); |
| 117 | + |
| 118 | +// Binary -> fail, Close -> close connection |
| 119 | +while (received.MessageType == WebSocketMessageType.Text) |
| 120 | +{ |
| 121 | +var text = Encoding.UTF8.GetString(receiveBuffer.Array, receiveBuffer.Offset, receiveBuffer.Count); |
| 122 | + |
| 123 | +// echo |
| 124 | +var sendingToken = CancellationToken.None; |
| 125 | +var sendingData = Encoding.UTF8.GetBytes(text); |
| 126 | +var sendingBuffer = new ArraySegment<byte>(sendingData); |
| 127 | +await socket.SendAsync(sendingBuffer, WebSocketMessageType.Text, true, sendingToken); |
| 128 | + |
| 129 | +received = await socket.ReceiveAsync(receiveBuffer, receiveToken); |
| 130 | +} |
| 131 | + |
| 132 | +var closeToken = CancellationToken.None; |
| 133 | +await socket.CloseAsync(received.CloseStatus.Value, received.CloseStatusDescription, closeToken); |
| 134 | +} |
| 135 | +} |
| 136 | +} |
| 137 | +else |
| 138 | +{ |
| 139 | +await next(); |
| 140 | +} |
| 141 | +}); |
| 142 | +}); |
| 143 | + |
| 144 | +/* |
| 145 | + * Broadcast example |
| 146 | + * Sends message to all connections until close connection |
| 147 | + * http://localhost:5000/Broadcast |
| 148 | + */ |
| 149 | +var allSockets = new ConcurrentBag<WebSocket>(); |
| 150 | + |
| 151 | +app.Map("/Broadcast", once => |
| 152 | +{ |
| 153 | +once.Use(async (context, next) => |
| 154 | +{ |
| 155 | +if (context.WebSockets.IsWebSocketRequest) |
| 156 | +{ |
| 157 | +// WebSocket request |
| 158 | +using (var socket = await context.WebSockets.AcceptWebSocketAsync()) |
| 159 | +{ |
| 160 | +if (socket?.State == WebSocketState.Open) |
| 161 | +{ |
| 162 | +allSockets.Add(socket); |
| 163 | + |
| 164 | +// Handle the socket |
| 165 | +var receiveToken = CancellationToken.None; |
| 166 | +var receiveBuffer = new ArraySegment<byte>(new byte[4096]); |
| 167 | + |
| 168 | +var received = await socket.ReceiveAsync(receiveBuffer, receiveToken); |
| 169 | + |
| 170 | +// Binary -> fail, Close -> close connection |
| 171 | +while (received.MessageType == WebSocketMessageType.Text) |
| 172 | +{ |
| 173 | +var text = Encoding.UTF8.GetString(receiveBuffer.Array, receiveBuffer.Offset, receiveBuffer.Count); |
| 174 | + |
| 175 | +// echo |
| 176 | +var sendingToken = CancellationToken.None; |
| 177 | +var sendingData = Encoding.UTF8.GetBytes(text); |
| 178 | +var sendingBuffer = new ArraySegment<byte>(sendingData); |
| 179 | + |
| 180 | +// send message to all connections |
| 181 | +await Task.WhenAll(allSockets.Where(x => x?.State == WebSocketState.Open) |
| 182 | +.Select(x => x.SendAsync(sendingBuffer, WebSocketMessageType.Text, true, sendingToken))); |
| 183 | + |
| 184 | +received = await socket.ReceiveAsync(receiveBuffer, receiveToken); |
| 185 | +} |
| 186 | + |
| 187 | +var closeToken = CancellationToken.None; |
| 188 | +await socket.CloseAsync(received.CloseStatus.Value, received.CloseStatusDescription, closeToken); |
| 189 | +} |
| 190 | +} |
| 191 | +} |
| 192 | +else |
| 193 | +{ |
| 194 | +await next(); |
| 195 | +} |
| 196 | +}); |
| 197 | +}); |
| 198 | + |
| 199 | +app.Run(async (context) => |
| 200 | +{ |
| 201 | +await context.Response.WriteAsync("WebSocket is available."); |
| 202 | +}); |
| 203 | +} |
| 204 | +} |
| 205 | +} |
0 commit comments