美文网首页
.Net Core 实现 WebSocket

.Net Core 实现 WebSocket

作者: Rinaloving | 来源:发表于2022-11-13 22:54 被阅读0次

说明

  • 今天发现在 IIS 上项目中的websocket 不通了,检查了一下,IIS中的也添加了websocket 的功能,其它项目环境部署上去websocket也是通的。在本地也是通的,这就让人很费解。之前项目发布使用独立发布的,后来改用debug发布就好了。
  • 项目环境(.net core 2.1 )
  • IIS 7 是不支持websocket 的,所以要7以上,这个也要注意。

引入空间

using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;

1. Startup.cs

           var webSocketOptions = new WebSocketOptions()
            {
                KeepAliveInterval = TimeSpan.FromSeconds(120),
                ReceiveBufferSize = 4 * 1024,
            };

            app.UseWebSockets(webSocketOptions);

            app.Use(async (context, next) =>
            {
                if (context.Request.Path == "/ws")
                {
                    if (context.WebSockets.IsWebSocketRequest)
                    {
                        WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
                        await Echo(context, webSocket);
                    }
                    else
                    {
                        context.Response.StatusCode = 400;
                        await next();
                    }
                }
                else
                {
                    await next();
                }
            });
        }



2. Echo

        private async Task Echo(HttpContext context, WebSocket webSocket)
        {
            var buffer = new byte[1024 * 4];
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            while (!result.CloseStatus.HasValue)
            {
                await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
                result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            }
            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }

3. Program.cs

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace WebTest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args).UseUrls("http://192.168.1.124:5006")
                .UseStartup<Startup>();
    }
}


4. 运行

相关文章

网友评论

      本文标题:.Net Core 实现 WebSocket

      本文链接:https://www.haomeiwen.com/subject/oayrxdtx.html