- 创建类WebSocketTest:
cs
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);
}
}
}
}
- 在program.cs中进行绑定
cs
/*创建一个WebSocket中间件,并将WebSocket请求路由到"/websocket/test"路径上。在处理WebSocket请求时,通过WebSocketTest.DoWork方法来处理连接和消息*/
app.UseWebSockets();
app.Map("/websocket/test", con => //当收到"/websocket/test"请求时,执行以下代码
{
con.UseWebSockets(); //中间件,启用websocket支持
con.Use(async (ctx, next) => //处理websocket请求时,执行以下逻辑
{
//创建监听websocket
WebSocketTest ws = new WebSocketTest();
await ws.DoWork(ctx);
await next.Invoke(); //执行下一个中间件
});
});
- 使用websocket在线工具模拟请求: