在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服务器,发送一条消息,然后接收并打印服务器返回的消息。