在C#中,要使用ClientWebSocket
類連接到WebSocket服務器,您需要首先安裝System.Net.WebSockets
NuGet包。然后,您可以按照以下步驟創建一個簡單的WebSocket客戶端:
using System;
using System.Net.WebSockets;
using System.Threading.Tasks;
public class WebSocketClient
{
private readonly string _url;
public WebSocketClient(string url)
{
_url = url;
}
public async Task ConnectAsync()
{
using (var client = new ClientWebSocket())
{
try
{
await client.ConnectAsync(_url, CancellationToken.None);
Console.WriteLine("Connected to WebSocket server.");
// 在這里發送和接收數據
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closed by client", CancellationToken.None);
}
}
}
public async Task SendMessageAsync(string message)
{
if (client != null && client.State == WebSocketState.Open)
{
var buffer = System.Text.Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
Console.WriteLine($"Sent message: {message}");
}
}
public async Task<string> ReceiveMessageAsync()
{
if (client != null && client.State == WebSocketState.Open)
{
var result = new StringBuilder();
var buffer = new byte[1024 * 4];
WebSocketReceiveResult receiveResult;
do
{
receiveResult = await client.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
result.Append(System.Text.Encoding.UTF8.GetString(buffer, 0, receiveResult.Count));
}
while (!receiveResult.CloseStatus.HasValue);
return result.ToString();
}
return null;
}
}
class Program
{
static async Task Main(string[] args)
{
var url = "ws://your-websocket-server-url";
var webSocketClient = new WebSocketClient(url);
await webSocketClient.ConnectAsync();
// 發送消息
await webSocketClient.SendMessageAsync("Hello, WebSocket server!");
// 接收消息
var message = await webSocketClient.ReceiveMessageAsync();
Console.WriteLine($"Received message: {message}");
}
}
請注意,您需要將your-websocket-server-url
替換為您的WebSocket服務器URL。運行此程序后,它將連接到WebSocket服務器,發送一條消息,然后接收并打印服務器返回的消息。