.Net6使用WebSocket与前端进行通信

1. 创建类WebSocketTest:

using System.Net.WebSockets;
using System.Text;

namespace WebSocket.Demo
{
    public class WebSocketTest
    {
        //当前请求实例
        System.Net.WebSockets.WebSocket socket =null;
        public async Task DoWork(HttpContext ctx)
        {
            socket = await ctx.WebSockets.AcceptWebSocketAsync();
            //执行监听
            await EchoLoop();
        }
        public async Task EchoLoop()
        {
            //创建缓存区
            var buffer = new byte[1024];
            var arraySeg = new ArraySegment(buffer);
            while (this.socket.State == WebSocketState.Open)
            {
                var incoming = await this.socket.ReceiveAsync(arraySeg, CancellationToken.None);
                //判断类型读取
                if (incoming.MessageType == WebSocketMessageType.Text)
                {
                    //incoming.Count  代表,请求内容字节数量
                    string userMessage = Encoding.UTF8.GetString(arraySeg.Array, 0, incoming.Count);
                    //接收客户端的字符串
                    userMessage = "客户端信息: " + userMessage + " 。时间: " +
                        DateTime.Now.ToLongTimeString();
                    ArraySegment segResult = new ArraySegment(Encoding.UTF8.GetBytes(userMessage));
                    await socket.SendAsync(segResult, WebSocketMessageType.Text, true, CancellationToken.None);
                }
                else
                {
                }

                byte[] backInfo = System.Text.UTF8Encoding.Default.GetBytes("服务端相应内容结束");
                var outgoing = new ArraySegment(backInfo, 0, backInfo.Length);
                await this.socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None);
            }
        }
    }
}

2. 在program.cs中进行绑定

app.UseWebSockets();
app.Map("/websocket/test", con =>
{
    con.UseWebSockets();
    con.Use(async (ctx, next) =>
    {
        //创建监听websocket
        WebSocketTest ws = new WebSocketTest();
        await ws.DoWork(ctx);
        await next.Invoke();
    });
});

3. 使用websocket在线工具模拟请求:

.Net6使用WebSocket与前端进行通信_第1张图片

你可能感兴趣的:(.net,websocket)