WebSockets
using var client = new ClientWebSocket();
// the websocket path is /stream
// if you are using SSL you also need to use the wss protocol and
// supply an API key in the x-api-key request header
var endpoint = "ws://127.0.0.1:8080/stream";
// var endpoint = "wss://127.0.0.1:8080/stream"; // for ssl
// client.Options.SetRequestHeader("x-api-key", /* your key */); // for ssl
await client.ConnectAsync(new Uri(endpoint), CancellationToken.None);
Console.WriteLine("Connected to WebSocket server.");
var buffer = new byte[4096];
while (client.State == WebSocketState.Open)
{
var result = await client.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Text)
{
string message = Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine(message);
}
else if (result.MessageType == WebSocketMessageType.Close)
{
await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
Console.WriteLine("Connection closed.");
}
}

Last updated
Was this helpful?

