WebSocket 服务器

关键字: WebSocket, 服务器

创建一个 WebSocket Server

首先,你需要先引用这个包 SuperSocket.WebSocket.Server

  1. dotnet add package SuperSocket.WebSocket.Server --version 2.0.0-*

然后添加下面的 using 语句

  1. using SuperSocket.WebSocket.Server;

让我创建这个 WebSocket 服务器,这个服务器将把收到的消息再发送回客户端:

  1. var host = WebSocketHostBuilder.Create()
  2. .UseWebSocketMessageHandler(
  3. async (session, message) =>
  4. {
  5. await session.SendAsync(message.Message);
  6. }
  7. )
  8. .ConfigureAppConfiguration((hostCtx, configApp) =>
  9. {
  10. configApp.AddInMemoryCollection(new Dictionary<string, string>
  11. {
  12. { "serverOptions:name", "TestServer" },
  13. { "serverOptions:listeners:0:ip", "Any" },
  14. { "serverOptions:listeners:0:port", "4040" }
  15. });
  16. })
  17. .ConfigureLogging((hostCtx, loggingBuilder) =>
  18. {
  19. loggingBuilder.AddConsole();
  20. })
  21. .Build();
  22. await host.RunAsync();

定义命令来处理消息

定义一个命令

  1. class ADD : IAsyncCommand<WebSocketSession, StringPackageInfo>
  2. {
  3. public async ValueTask ExecuteAsync(WebSocketSession session, StringPackageInfo package)
  4. {
  5. var result = package.Parameters
  6. .Select(p => int.Parse(p))
  7. .Sum();
  8. await session.SendAsync(result.ToString());
  9. }
  10. }

注册这个命令

  1. builder
  2. .UseCommand<StringPackageInfo, StringPackageConverter>(commandOptions =>
  3. {
  4. // register commands one by one
  5. commandOptions.AddCommand<ADD>();
  6. });

类型参数 StringPackageConverter 是能够将 WebSocketPackage 转化成你自己的应用程序包的转化器的类型。

  1. class StringPackageConverter : IPackageMapper<WebSocketPackage, StringPackageInfo>
  2. {
  3. public StringPackageInfo Map(WebSocketPackage package)
  4. {
  5. var pack = new StringPackageInfo();
  6. var arr = package.Message.Split(' ', 3, StringSplitOptions.RemoveEmptyEntries);
  7. pack.Key = arr[0];
  8. pack.Parameters = arr.Skip(1).ToArray();
  9. return pack;
  10. }
  11. }