天天看点

asp.net core WebSocket的使用

ASP.NET Core中使用WebSocket可以实现双向通信,以下是ASP.NET Core WebSocket的使用步骤:

创建WebSocketMiddleware

创建一个自定义的WebSocketMiddleware来处理WebSocket请求,代码如下所示:

public class WebSocketMiddleware
{
 private readonly RequestDelegate _next;
 public WebSocketMiddleware(RequestDelegate next)
 {
 _next = next;
 }
 public async Task Invoke(HttpContext context)
 {
if (context.WebSockets.IsWebSocketRequest)
 {
 WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
 await EchoAsync(context, webSocket);
 }
else
 {
 await _next(context);
 }
 }
 private async Task EchoAsync(HttpContext context, WebSocket webSocket)
 {
 var buffer = new byte[1024 * 4];
while (webSocket.State == WebSocketState.Open)
 {
 var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Text)
 {
 var incomingMessage = Encoding.UTF8.GetString(buffer, 0, result.Count);
 var outgoingMessage = "You sent " + incomingMessage + " at " + DateTime.Now.ToLongTimeString();
 var outgoingBuffer = Encoding.UTF8.GetBytes(outgoingMessage);
 await webSocket.SendAsync(new ArraySegment<byte>(outgoingBuffer, 0, outgoingBuffer.Length), result.MessageType, result.EndOfMessage, CancellationToken.None);
 }
else if (result.MessageType == WebSocketMessageType.Close)
 {
 await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
 }
 }
 }
}
           

注册WebSocketMiddleware

在Startup.cs文件的Configure方法中注册WebSocketMiddleware,代码如下所示:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
 app.UseRouting();
 app.UseEndpoints(endpoints =>
 {
 endpoints.MapGet("/", async context =>
 {
 await context.Response.WriteAsync("Hello World!");
 });
 endpoints.MapMiddleware<WebSocketMiddleware>("/ws");
 });
}

           

连接WebSocket

使用JavaScript代码连接WebSocket,代码如下所示:

var ws = new WebSocket("ws://" + location.host + "/ws");
ws.onopen = function () {
 console.log("WebSocket connection opened.");
};
ws.onmessage = function (event) {
 console.log("Received message: " + event.data);
};
ws.onclose = function () {
 console.log("WebSocket connection closed.");
};
ws.send("Hello, WebSocket!");
           

以上是ASP.NET Core中使用WebSocket的简单示例,通过WebSocket可以实现双向通信,可以在实时通讯、在线游戏等领域中得到广泛应用。