- 命名空间 System.Net.WebSockets
- 代码
using (var ws = new ClientWebSocket())
{
await ws.ConnectAsync(new Uri(url), CancellationToken.None);
while (ws.State == WebSocketState.Open)
{
var result = new byte[1024];
await ws.ReceiveAsync(new ArraySegment<byte>(result), new CancellationToken());//接受数据
var msg = Encoding.UTF8.GetString(result, 0, result.Length);
Console.WriteLine(msg);
}
}
- 缺点:返回数据量长可能导致 byte 数据截断