在C#中,你可以使用System.Net.WebSockets
命名空間中的類來實現WebSocket通信
首先,確保你的項目已經引用了System.Net.WebSockets
。
創建一個WebSocket客戶端:
using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
namespace WebSocketClientExample
{
class Program
{
static async Task Main(string[] args)
{
await ConnectToWebSocketServer();
}
private static async Task ConnectToWebSocketServer()
{
using var client = new ClientWebSocket();
Uri uri = new Uri("wss://example.com/websocket"); // 替換為你的WebSocket服務器地址
try
{
await client.ConnectAsync(uri, CancellationToken.None);
Console.WriteLine("Connected to WebSocket server.");
}
catch (Exception ex)
{
Console.WriteLine($"Error connecting to WebSocket server: {ex.Message}");
return;
}
// 發送消息
string message = "Hello, WebSocket!";
byte[] buffer = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
// 接收消息
byte[] receiveBuffer = new byte[1024];
WebSocketReceiveResult result = await client.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
string receivedMessage = Encoding.UTF8.GetString(receiveBuffer, 0, result.Count);
Console.WriteLine($"Received message: {receivedMessage}");
// 關閉連接
await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Bye", CancellationToken.None);
}
}
}
注意:這個示例僅用于演示目的,實際應用中你可能需要處理更復雜的場景,例如錯誤處理、心跳檢測等。此外,你還可以考慮使用第三方庫,如Microsoft.AspNetCore.Http.Abstractions
,它提供了更高級的功能和更好的性能。