官方學習資料:WebSocket服務器。
本文開發環境:Win10 + VS2019 + .NetCore 3.1 + SuperSocket.WebSocket.Server 2.0.0-beta.8。
Gitee:SuperSocketV2Sample。
WebSocket服務器使用WebSocketHostBuilder類創建,可使用鏈式函數設置消息回調處理、WebSocket參數配置等。如果要添加自定義命令,那么需要把WebSocketPackage轉換為StringPackageInfo,Demo中的StringPackageConverter就是實現這個轉換的類。
需要注意的是,命令類繼承自IAsyncCommand<WebSocketSession, StringPackageInfo>,和之前的基類IAsyncCommand<StringPackageInfo>有所不同。命令類的實現請參考Gitee項目源碼。
此外,如果使用UseCommand注冊了命令,無論UseCommand回調方法中是否注冊命令,UseWebSocketMessageHandler方法都不會被調用。
1、StringPackageConverter
using System; using System.Linq; using SuperSocket.Command; using SuperSocket.ProtoBase; using SuperSocket.WebSocket; namespace SuperSocketV2Sample.WebSocketServer.Server { /// <summary> /// WebSocketPackage轉換器 /// </summary> public class StringPackageConverter : IPackageMapper<WebSocketPackage, StringPackageInfo> { public StringPackageInfo Map(WebSocketPackage package) { var packInfo = new StringPackageInfo(); var array = package.Message.Split(' ', 3, StringSplitOptions.RemoveEmptyEntries); packInfo.Key = array[0]; packInfo.Parameters = array.Skip(1).ToArray(); packInfo.Body = string.Join(' ', packInfo.Parameters); return packInfo; } } }
2、Program
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using SuperSocket.Command; using SuperSocket.ProtoBase; using SuperSocket.WebSocket.Server; using SuperSocketV2Sample.WebSocketServer.Commands; using SuperSocketV2Sample.WebSocketServer.Server; namespace SuperSocketV2Sample.WebSocketServer { class Program { static async Task Main() { var host = WebSocketHostBuilder.Create() //注冊WebSocket消息處理器(使用UseCommand注冊命令之后該處理器不起作用) .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); }) .UseCommand<StringPackageInfo, StringPackageConverter>(commandOptions => { //注冊命令 commandOptions.AddCommand<AddCommand>(); commandOptions.AddCommand<DivCommand>(); commandOptions.AddCommand<MulCommand>(); commandOptions.AddCommand<SubCommand>(); commandOptions.AddCommand<EchoCommand>(); }) .ConfigureAppConfiguration((hostCtx, configApp) => { configApp.AddInMemoryCollection(new Dictionary<string, string> { {"serverOptions:name", "TestServer"}, {"serverOptions:listeners:0:ip", "Any"}, {"serverOptions:listeners:0:port", "4040"} }); }) .ConfigureLogging((hostCtx, loggingBuilder) => { //添加控制台輸出 loggingBuilder.AddConsole(); }) .Build(); await host.RunAsync(); } } }