使用SuperSocket做WebSocket服务器开发需要引用包SuperSocket.WebSocket.Server,本文简称SuperWebScoket。
本文环境为.Net5 + ASP.Net Core Web API + SuperSocket.WebSocket.Server 2.0.0-beta.10,介绍了如何在在.NetCore WebAPI中使用SuperWebScoket的方法,以及如何启动WebSocket。
本文假设读者具有.NetCore Web API及SuperWebScoket的使用经验。
1、创建自定义WebScoket服务
WebScoket服务主要对WebScoket的配置进行设置,使用了内存配置代替传统的配置文件,通过在WebAPI项目中设置WebScoket端口,实现了端口的动态配置。
此外,参考《在WPF中集成SuperSocket 2.0》,WebScoket服务也在关闭IHost时执行了Dispose方法。不过,作为服务端程序,WebScoket服务一般不会关闭,直到所在的进程退出。
public interface IWebSocketServerService { Task Startup(); Task Shutdown(); } public class WebSocketServerService : IWebSocketServerService { private IHost _host; private readonly ILogger<WebSocketServerService> _logger; private readonly int _port; public WebSocketServerService(ILogger<WebSocketServerService> logger, IConfiguration configuration) { _logger = logger; var port = configuration["WebSocketServer:Port"]; if (!int.TryParse(port, out _port)) { _port = 6666; _logger.LogWarning($"读取WebSocketServerPort失败,默认监听端口{_port}."); } } public async Task Startup() { try { _host = WebSocketHostBuilder.Create() //注册WebSocket消息处理器 .UseWebSocketMessageHandler(async (session, package) => { Console.WriteLine($@"{DateTime.Now:yyyy-MM-dd HH:mm:ss fff} Receive message: {package.Message}."); //Send message back var message = $@"{DateTime.Now:yyyy-MM-dd HH:mm:ss fff} Hello from WebSocket Server: {package.Message}."; await session.SendAsync(message); }) .ConfigureAppConfiguration((hostCtx, configApp) => { configApp.AddInMemoryCollection(new Dictionary<string, string> { {"serverOptions:name", "NwMesServer"}, {"serverOptions:listeners:0:ip", "Any"}, {"serverOptions:listeners:0:port", $"{_port}"} }); }) .ConfigureLogging((hostCtx, loggingBuilder) => { //添加控制台输出 loggingBuilder.AddConsole(); }) .Build(); await _host.RunAsync(); } catch (Exception e) { _logger.LogError($"启动WebSocketServer失败:{e.GetMessageWithInnerException()}."); } } public async Task Shutdown() { try { await _host.StopAsync(); } catch (Exception e) { _logger.LogError($"关闭WebSocketServer失败:{e.Message}."); } finally { _host.Dispose(); } } }
2、注册WebScoket服务
在Startup.cs的ConfigureServices方法中注入即可。
public void ConfigureServices(IServiceCollection services) { //注入服务 services.AddScoped<IMd5Service, Md5Service>(); services.AddSingleton<IWebSocketServerService, WebSocketServerService>(); }
3、启动WebSocket服务
在Startup.cs的Configure方法中启动WebScoket服务。
public async void Configure(IApplicationBuilder app, IWebHostEnvironment env) { ... app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); //启动WebSocket服务 var webSocketServerService = app.ApplicationServices.GetService<IWebSocketServerService>(); await webSocketServerService.Startup(); }