背景:SuperSocket支持WebSocket应用层协议,记录一下怎样使用
一.首先引用相关Nuget包
二、创建WebSocketHostBuilder
var host = WebSocketHostBuilder.Create().UseWebSocketMessageHandler(
async (session, message) =>
{
await session.SendAsync(message.Message);
}
)
.ConfigureLogging((hostCtx, loggingBuilder) =>
{
loggingBuilder.AddConsole();
})
.Build();
await host.RunAsync();
Server相关配置在appsettings.json中的serverOptions
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"serverOptions": {
"name": "TestServer",
"listeners": [
{
"ip": "Any",
"port": "2020"
},
{
"ip": "Any",
"port": "2021"
}
]
}
}
这样就搭建好了
三、使用Command
?编写你的Command方法(和普通Socket有一点不一样,是WebSocketSession不是IAppSession):
public class Del : IAsyncCommand<WebSocketSession, MyPackage>
{
public async ValueTask ExecuteAsync(WebSocketSession session, MyPackage package)
{
//TODO 你的业务
string sql = $" delete Users where UserName='{package.UserName}')";
Thread.Sleep(2000);
await session.SendAsync(Encoding.UTF8.GetBytes(package.UserName));
}
}
?在builder中注册Command:
.UseCommand<MyPackage, StringPackageConverter>(commandOptions =>
{
// register commands one by one
commandOptions.AddCommand<Del>();
})
编写WebSocketPackage和你的Pakcge的转换方法:
public class StringPackageConverter : IPackageMapper<WebSocketPackage, MyPackage>
{
public MyPackage Map(WebSocketPackage package)
{
var pack = new MyPackage();
var arr = package.Message.Split(' ', 3, StringSplitOptions.RemoveEmptyEntries);
pack.Key = arr[0];
pack.UserName = arr[1];
return pack;
}
}
这样就使用了Command
?
?
?
|