I am trying to implement a WebSocket, but every time I try to read it throws a "The remote party closed the WebSocket connection without completing the close handshake." error.
This is my code:
string url = "wss://ws.url.com/v1/func/func2";
var param = new Dictionary<string, string>()
{
{ "apikey", "apikey" }
};
Uri uri = new Uri(QueryHelpers.AddQueryString(url, param));
CancellationToken token = CancellationToken.None;
using (var client = new ClientWebSocket() { Options = { KeepAliveInterval = new TimeSpan(0, 0, 3, 0) } })
{
client.ConnectAsync(uri, token).Wait();
Subscribe(client, token).Wait();
}
public static async Task Subscribe(ClientWebSocket client, CancellationToken token)
{
StringBuilder message = new StringBuilder("{\"action\":\"subscribe\",\"params\":{\"param\":\"value\"}}");
Console.WriteLine("Subscribe : " + message.ToString());
var sendBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(message.ToString()));
await client.SendAsync(sendBuffer, WebSocketMessageType.Text, true, token);
ArraySegment<byte> receivedBytes = new ArraySegment<byte>(new byte[1024]);
WebSocketReceiveResult result = await client.ReceiveAsync(receivedBytes, token);
Console.WriteLine(Encoding.UTF8.GetString(receivedBytes.Array, 0, result.Count));
}
The connection remains open until ReadAsync, where it gets aborted and I receive an "The remote party closed the WebSocket connection without completing the close handshake." error. I've scoured the internet but I can't find a solution to this. I am supposed to get a message back after subscribing, but it's not working, and it looks like the internet knows much about this.
The WebSocket server is the very popular TwelveData financial API, so it's expected to work well.
Because of the exception I cannot read any data at all.
Subscriptions are limited to prime keys. Make sure you use one of those.