在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
,它提供了更高级的功能和更好的性能。