中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

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
仙桃市| 乌兰县| 防城港市| 内乡县| 永安市| 张家川| 阜阳市| 东光县| 香港| 潼南县| 济阳县| 区。| 邢台市| 治县。| 南郑县| 巴彦县| 三台县| 夹江县| 叶城县| 当雄县| 万荣县| 佳木斯市| 兴化市| 大田县| 三明市| 松阳县| 潞城市| 买车| 镇坪县| 海阳市| 舟山市| 江城| 东安县| 大兴区| 渝北区| 平度市| 札达县| 合川市| 微博| 金溪县| 巴南区|