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中进行绑定
/*创建一个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(); //执行下一个中间件
});
});
3. 使用websocket在线工具模拟请求:文章来源:https://www.toymoban.com/news/detail-771498.html
文章来源地址https://www.toymoban.com/news/detail-771498.html
到了这里,关于.Net6使用WebSocket与前端进行通信的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!