亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

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
砚山县| 年辖:市辖区| 沂南县| 漠河县| 南通市| 六安市| 手机| 昆明市| 淳安县| 长沙县| 巴南区| 双柏县| 邯郸县| 县级市| 洛浦县| 鹤岗市| 蒙城县| 蓬溪县| 色达县| 崇信县| 楚雄市| 平顶山市| 秀山| 大英县| 贞丰县| 老河口市| 柳州市| 济阳县| 青冈县| 汪清县| 油尖旺区| 宁陕县| 天台县| 嘉义市| 莒南县| 巴林右旗| 鄯善县| 永泰县| 祁连县| 莱西市| 简阳市|