c#

C# websocketserver怎么保持连接

小樊
102
2024-07-16 15:51:47
栏目: 编程语言

要保持连接,您可以使用心跳机制来定期发送消息以确保连接保持活动状态。以下是一个简单的示例代码,演示如何使用C#编写一个WebSocket服务器并实现心跳功能:

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

class WebSocketServer
{
    private HttpListener listener;
    private CancellationTokenSource cancellationTokenSource;

    public async Task Start(string url)
    {
        listener = new HttpListener();
        listener.Prefixes.Add(url);
        listener.Start();

        Console.WriteLine("Server started");

        while (true)
        {
            HttpListenerContext context = await listener.GetContextAsync();
            if (context.Request.IsWebSocketRequest)
            {
                ProcessWebSocketRequest(context);
            }
            else
            {
                context.Response.StatusCode = 400;
                context.Response.Close();
            }
        }
    }

    private async Task ProcessWebSocketRequest(HttpListenerContext context)
    {
        WebSocketContext webSocketContext = await context.AcceptWebSocketAsync(null);
        WebSocket webSocket = webSocketContext.WebSocket;

        // Start a task to keep the connection alive
        cancellationTokenSource = new CancellationTokenSource();
        Task.Run(async () =>
        {
            while (webSocket.State == WebSocketState.Open)
            {
                try
                {
                    await webSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("Ping")), WebSocketMessageType.Text, true, cancellationTokenSource.Token);
                    await Task.Delay(5000); // Send ping every 5 seconds
                }
                catch (WebSocketException)
                {
                    break;
                }
            }
        });

        // Handle incoming messages
        byte[] buffer = new byte[1024];
        while (webSocket.State == WebSocketState.Open)
        {
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cancellationTokenSource.Token);
            if (result.MessageType == WebSocketMessageType.Close)
            {
                break;
            }
            else if (result.MessageType == WebSocketMessageType.Text)
            {
                string message = Encoding.UTF8.GetString(buffer, 0, result.Count);
                Console.WriteLine("Received message: " + message);
            }
        }

        await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
    }

    public void Stop()
    {
        cancellationTokenSource?.Cancel();
        listener.Stop();
        listener.Close();
    }
}

class Program
{
    static async Task Main(string[] args)
    {
        WebSocketServer server = new WebSocketServer();
        await server.Start("http://localhost:8080/");
    }
}

在上面的示例中,我们创建了一个简单的WebSocket服务器,并在每5秒发送一个"Ping"消息以保持连接活动状态。您可以根据需求调整心跳间隔和消息内容。在客户端断开连接时,服务器会停止心跳并关闭连接。

0
看了该问题的人还看了