温馨提示×

asp.net websocket啥技巧

小樊
81
2024-11-23 06:06:17
栏目: 编程语言

ASP.NET Core WebSocket 提供了一种在客户端和服务器之间进行全双工通信的机制。以下是一些使用 ASP.NET Core WebSocket 的技巧:

  1. 安装依赖项:确保安装了 Microsoft.AspNetCore.Http.AbstractionsMicrosoft.AspNetCore.WebSockets NuGet 包。

  2. 配置 WebSocket:在 Startup.cs 文件中配置 WebSocket 中间件。

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.AddWebSocket(options =>
        {
            options.AllowedOrigins = new[] { "*" };
        });
    }
    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapWebSocket("/ws", new WebSocketOptions() { KeepAliveInterval = TimeSpan.Zero });
        });
    }
    
  3. 处理 WebSocket 连接:创建一个类来处理 WebSocket 连接和消息。

    public class MyWebSocketHandler
    {
        private readonly WebSocket _webSocket;
    
        public MyWebSocketHandler(WebSocket webSocket)
        {
            _webSocket = webSocket;
        }
    
        public async Task OnConnectedAsync(string userId)
        {
            await _webSocket.SendAsync(Encoding.UTF8.GetBytes($"Welcome, {userId}!"));
        }
    
        public async Task OnMessageReceivedAsync(string message)
        {
            var data = Encoding.UTF8.GetString(message);
            await _webSocket.SendAsync(Encoding.UTF8.GetBytes($"Echo: {data}"));
        }
    
        public async Task OnDisconnectedAsync(Exception exception)
        {
            Console.WriteLine($"Disconnected: {exception}");
        }
    }
    
  4. 在控制器中使用 WebSocket:在控制器中处理 WebSocket 请求。

    [HttpGet]
    public async Task<IActionResult> Index(string id)
    {
        if (HttpContext.WebSockets.IsWebSocketRequest())
        {
            var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
            var handler = new MyWebSocketHandler(webSocket);
            await handler.OnConnectedAsync(id);
    
            while (webSocket.State == WebSocketState.Open)
            {
                var buffer = new byte[1024 * 4];
                WebSocketReceiveResult result;
                do
                {
                    result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                }
                while (!result.CloseStatus.HasValue);
    
                var message = Encoding.UTF8.GetString(buffer, 0, result.Count);
                await handler.OnMessageReceivedAsync(message);
            }
    
            await handler.OnDisconnectedAsync(null);
        }
    
        return View();
    }
    
  5. 客户端代码:在客户端使用 JavaScript 建立 WebSocket 连接。

    <!DOCTYPE html>
    <html>
    <head>
        <title>WebSocket Example</title>
    </head>
    <body>
        <input type="text" id="userId" placeholder="Enter your ID">
        <script>
            const userId = document.getElementById("userId").value;
            const socket = new WebSocket("ws://localhost:5000/ws");
    
            socket.addEventListener("open", (event) => {
                socket.send(JSON.stringify({ userId }));
            });
    
            socket.addEventListener("message", (event) => {
                const data = JSON.parse(event.data);
                console.log(`Server says: ${data}`);
            });
    
            socket.addEventListener("close", (event) => {
                console.log(`Disconnected: ${event}`);
            });
        </script>
    </body>
    </html>
    

这些技巧可以帮助你更好地使用 ASP.NET Core WebSocket 进行实时通信。

0