1. 参考资料
2. 程序A : 没有使用中间件 (https://www.cnblogs.com/u-drive/p/9833634.html)
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; namespace AspNetCoreWithWebSocketDemo { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); //Be sure to configure before mvc middleware. app.UseWebSockets(); app.Use(async (context, next) => { if (context.WebSockets.IsWebSocketRequest) { using (IServiceScope scope = app.ApplicationServices.CreateScope()) { WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); Console.WriteLine("接收到玩家链接" + context.Request.HttpContext.Connection.RemoteIpAddress.ToString()); //The AcceptWebSocketAsync method upgrades the TCP connection to a WebSocket connection and provides a WebSocket object. Use the WebSocket object to send and receive messages await Echo(context, webSocket); } } else { //Hand over to the next middleware await next(); } }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } private async Task Echo(HttpContext context, WebSocket webSocket) //Echo 响应的意思 { var buffer = new byte[1024 * 4]; WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); string receiveText = System.Text.Encoding.Default.GetString(buffer); Console.WriteLine($"收到客户端的信息 {context.Request.HttpContext.Connection.RemoteIpAddress}:{context.Request.HttpContext.Connection.RemotePort} {receiveText}" ); while (!result.CloseStatus.HasValue) { string s = DateTime.Now.ToString(); byte[] sendContext = System.Text.Encoding.Default.GetBytes(s); //await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None); await webSocket.SendAsync(new ArraySegment<byte>(sendContext, 0, sendContext.Length), WebSocketMessageType.Text, true, CancellationToken.None); result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); } await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None); Console.WriteLine($"客户端断开链接"); } } }