asp.net api添加websocket

烂柯 发布于 2024-03-29 61 次阅读


一、概述

​ 业务场景中需要消息回响,所以简单记录下通过asp.net core默认websocket中间件添加websocket协议。asp.net core中websocket支持

二、配置及处理消息

1、添加中间件

program.cs

var webSocketOptions = new WebSocketOptions
{
    //不配置,默认也是2分钟
    KeepAliveInterval = TimeSpan.FromMinutes(2)
};
app.UseWebSockets(webSocketOptions);

2、添加请求接口

WebSocketController.cs

[HttpGet,Route("ws")]
public async Task GetAsync(CancellationToken cancellationToken)
{
    HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
    if (!HttpContext.WebSockets.IsWebSocketRequest)
        return;
    using WebSocket webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
    TaskCompletionSource socketFinishedTcs = new TaskCompletionSource();
    EchoAsync(webSocket, socketFinishedTcs, cancellationToken);
    await socketFinishedTcs.Task;
}

3、添加消息处理

如果需要管理

private async Task EchoAsync(WebSocket webSocket, TaskCompletionSource socketFinishedTcs, CancellationToken cancellationToken)
{
    //设置消息缓冲区
    ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024 * 1024]);
    //设置消息缓存
    IList<byte[]> bufferMessage = new List<byte[]>();
    //接收消息
    WebSocketReceiveResult receiveResult;
    do
    {
        receiveResult = await webSocket.ReceiveAsync(buffer, cancellationToken);
        bufferMessage.Add(buffer.Take(receiveResult.Count).ToArray());
        if (!receiveResult.EndOfMessage)
            continue;
        await webSocket.SendAsync(bufferMessage.SelectMany(p => p).ToArray(), WebSocketMessageType.Text, true, cancellationToken);
        bufferMessage.Clear();

    } while (!receiveResult.CloseStatus.HasValue);
    socketFinishedTcs.SetResult();
}

三、配置nginx代理

map $http_upgrade $connection_upgrade {
   default upgrade;
   '' close;
}
upstream message_backend {
   server 192.168.1.2:2345;
}
server
{
    listen 80;
    listen 443 ssl http2;
    server_name test;
    index index.php index.html index.htm default.php default.htm default.html;
    root /www/wwwroot/test;
    location /api/msg/Synergy/Hub {
      proxy_pass http://message_backend;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection $connection_upgrade;
    }
}
烂柯

最后更新于 2025-02-18