• 欢迎光临~

netcore的webscoket实时通信

开发技术 开发技术 2022-07-18 次浏览

首先在startup的Configure添加

app.UseWebSockets(new WebSocketOptions
        {
            KeepAliveInterval = new TimeSpan(0, 0, 15)
        });

添加一个控制器

[Route("api/[controller]")]
[ApiController]
public class WebScoketHandleController: ControllerBase
{
    //private readonly SLIMSContext _context;
    public WebScoketHandleController()
    {
        
    }/// <summary>
    /// webscoket地址
    /// </summary>
    /// <returns></returns>
    [HttpGet("/ws")]
    public async Task Get()
    {
        if (HttpContext.WebSockets.IsWebSocketRequest)
        {
            using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
           // _logger.Log(LogLevel.Information, "WebSocket connection established");
            await Echo(webSocket);
        }
        else
        {
            HttpContext.Response.StatusCode = 400;
        }
    }

    private async Task Echo(WebSocket webSocket)
    {
        var buffer = new byte[1024 * 4];
        var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
        //_logger.Log(LogLevel.Information, "Message received from Client");

        while (!result.CloseStatus.HasValue)
        {
            var serverMsg = Encoding.UTF8.GetBytes($"Server: Hello. You said: {Encoding.UTF8.GetString(buffer)}");
            await webSocket.SendAsync(new ArraySegment<byte>(serverMsg, 0, serverMsg.Length), result.MessageType, result.EndOfMessage, CancellationToken.None);
            //_logger.Log(LogLevel.Information, "Message sent to Client");

            result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            //_logger.Log(LogLevel.Information, "Message received from Client");

        }
        await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        //_logger.Log(LogLevel.Information, "WebSocket connection closed");
    }
}

调用ws://IP地址:端口/ws

程序员灯塔
转载请注明原文链接:netcore的webscoket实时通信
喜欢 (0)