您好,登錄后才能下訂單哦!
在C#中,使用WebSocket進行實時通信是一種常見的方法。為了優雅地處理WebSocket消息確認,你可以采用以下步驟:
System.Net.WebSockets
命名空間中的HttpListener
類來實現這個功能。以下是一個簡單的WebSocket服務器示例:using System;
using System.Net;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
namespace WebSocketServer
{
class Program
{
static async Task Main(string[] args)
{
var listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();
while (true)
{
var context = await listener.GetContextAsync();
if (context.Request.IsWebSocketRequest)
{
ProcessWebSocketRequest(context);
}
}
}
private static async void ProcessWebSocketRequest(HttpListenerContext context)
{
var webSocketContext = await context.AcceptWebSocketAsync(null);
var webSocket = webSocketContext.WebSocket;
var buffer = new byte[1024 * 4];
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
// Process the received message
var message = Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine($"Received: {message}");
// Send a confirmation message
var confirmationMessage = "Message received";
var confirmationBuffer = Encoding.UTF8.GetBytes(confirmationMessage);
await webSocket.SendAsync(new ArraySegment<byte>(confirmationBuffer), WebSocketMessageType.Text, true, CancellationToken.None);
// Wait for the next message
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
}
}
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WebSocketClient
{
class Program
{
static async Task Main(string[] args)
{
var client = new ClientWebSocket();
await client.ConnectAsync(new Uri("ws://localhost:8080"), CancellationToken.None);
// Send a message to the server
var message = "Hello, WebSocket!";
var messageBuffer = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(messageBuffer), WebSocketMessageType.Text, true, CancellationToken.None);
// Wait for the server's confirmation message
var buffer = new byte[1024 * 4];
var result = await client.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
var confirmationMessage = Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine($"Server: {confirmationMessage}");
await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Bye", CancellationToken.None);
}
}
}
注意:這些示例僅用于演示目的。在實際項目中,你可能需要添加錯誤處理、日志記錄等功能。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。