SuperSocket 2.0学习07:WebSocket服务器

官方学习资料: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();
        }
    }
}

SuperSocket 2.0学习07:WebSocket服务器

上一篇:bugku web14 flag在index中


下一篇:html file类型如何一次性上传多个文件