Get Data from WebSocket using .Net ClientWebSocket

7.2k views Asked by At

I need to collect data from a WebSocket.

If I try to test the websocket with this site: http://www.websocket.org/echo.html I can connect and send message without problem but when I try to connect to the websocket using .Net Framework libraries I get:

System.Net.WebException: Internal Server Error (500).

The code I use to connect is this:

        string uri = "wss://wss.xxx.xxx";
        ClientWebSocket webSocket = null;
        try
        {
            webSocket = new ClientWebSocket();
            await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
            await Task.WhenAll(Receive(webSocket), Send(webSocket));
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: {0}", ex);
        }

If I try to connect to any other web socket, the code works well...

The difference with the other websocket is that the address starts with "wss" instead of "ws" ( think its because of secure connection).

If I test with a browser like Chrome the websocket connetion works, but not in .Net, may be I have to add some header in order to simulate a Browser Agent ?

Thanks to support

1

There are 1 answers

0
DarioN1 On BEST ANSWER

Finally After some search I find out the problem: I just had to add headers to the ClientWebSocket.

The problem is that ClientWebSocket doesn't provide methods to add specific headers and I had to make a force of ClientWebSocket.

This thread help me a lot to solve my problem:

Setting "User-Agent" HTTP header in ClientWebSocket

Using this new version of ClientWebSocket I was able to add Headers.