91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

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
潍坊市| 濮阳县| 孝感市| 翁源县| 垣曲县| 嵩明县| 凌源市| 黄平县| 邢台市| 上高县| 永兴县| 冕宁县| 卓资县| 集贤县| 瑞金市| 保靖县| 衡南县| 余庆县| 清新县| 金坛市| 吉水县| 固始县| 进贤县| 浪卡子县| 巨鹿县| 天等县| 峨边| 五指山市| 安图县| 鸡泽县| 正蓝旗| 孟津县| 闻喜县| 景洪市| 东海县| 红河县| 阿拉善左旗| 宣汉县| 邯郸县| 寿宁县| 邹平县|