要保持連接,您可以使用心跳機制來定期發(fā)送消息以確保連接保持活動狀態(tài)。以下是一個簡單的示例代碼,演示如何使用C#編寫一個WebSocket服務器并實現(xiàn)心跳功能:
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/");
}
}
在上面的示例中,我們創(chuàng)建了一個簡單的WebSocket服務器,并在每5秒發(fā)送一個"Ping"消息以保持連接活動狀態(tài)。您可以根據(jù)需求調整心跳間隔和消息內(nèi)容。在客戶端斷開連接時,服務器會停止心跳并關閉連接。