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<byte>(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<byte> segResult = new ArraySegment<byte>(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<byte>(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) =>{//创建监听websocketWebSocketTest ws = new WebSocketTest();await ws.DoWork(ctx);await next.Invoke();});
});
3. 使用websocket在线工具模拟请求: