websocket-sharp icon indicating copy to clipboard operation
websocket-sharp copied to clipboard

How to catch exceptions that occur in websocket sharp

Open PaulGWebster opened this issue 5 years ago • 5 comments

Good day I keep hitting an exception after a few hours of use;

22/11/2020 13:03:07|Fatal|WebSocket.<startReceiving>b__176_2|WebSocketSharp.WebSocketException: The header of a frame cannot be read from the stream.
                             at WebSocketSharp.WebSocketFrame.processHeader(Byte[] header)
                             at WebSocketSharp.WebSocketFrame.<>c__DisplayClass73_0.<readHeaderAsync>b__0(Byte[] bytes)
                             at WebSocketSharp.Ext.<>c__DisplayClass48_0.<ReadBytesAsync>b__0(IAsyncResult ar)
Websocket closed connection

I tried wrapping my entire websocket initialisation and OnBinds in a try {} catch {} but the exception still halts the entire program, what is the correct watch to catch this ... or alternatively catch everything from websocketsharp, basically on failure/error the thread is restarted by main; but it never gets chance as the entire program exits

Example code block (with trys that do not work):

        private void gdaxWebSocketFeed(object passedArgs)
        {
            object[] passedArgsArray = (object[])passedArgs;
​
            ulong packetID = 0;
            int websocketID = (int)passedArgsArray[0];
            Dictionary<int,ConcurrentQueue<string>> sendQueue = 
                (Dictionary<int,ConcurrentQueue<string>>)passedArgsArray[1];
            string wsHost = (string)passedArgsArray[2];
​
            try
            {
                WebSocket wsClient = new WebSocket(wsHost);
                //wsClient.SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
​
                wsClient.OnOpen += (sender, e) =>
                {
                    parentFunction("OPEN", packetID++, new object[] { websocketID, e });
                };
                wsClient.OnError += (sender, e) =>
                {
                    parentFunction("ERROR", packetID++, new object[] { websocketID, "error", e });
                };
                wsClient.OnClose += (sender, e) =>
                {
                    parentFunction("CLOSE", packetID++, new object[] { websocketID, e });
                };
                wsClient.OnMessage += (sender, e) =>
                {
                    GDAXExchangePacket CastJSON =
                        JsonConvert.DeserializeObject<GDAXExchangePacket>(e.Data);
                    parentFunction("MESSAGE", packetID++, new object[] { websocketID, CastJSON, e.Data });
                };
​
                wsClient.Connect();
​
                while (wsClient.IsAlive)
                {
                    if (sendQueue.Count == 0)
                    {
                        Thread.Sleep(100);
                    }
                    else if (sendQueue[websocketID].TryDequeue(out string sendData))
                    {
                        if (sendData != null)
                        {
                            wsClient.Send(sendData);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                parentFunction("ERROR", packetID++, new object[] { websocketID, "exception", exception.Message });
            }
        }

PaulGWebster avatar Nov 22 '20 13:11 PaulGWebster

I have the same error: "The header of a frame cannot be read from the stream"

Do yo know how to fix it?

mzumbo avatar Jan 13 '21 15:01 mzumbo

Yes downgrade the secure websocket to a standard websocket, nginx (gdax for my case):

    server {
        listen       10.200.200.1:8000;

        proxy_ssl_server_name on;

        location / {
                proxy_pass https://ws-feed.pro.coinbase.com;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "Upgrade";
                proxy_http_version 1.1;
                proxy_set_header Host "ws-feed.pro.coinbase.com";
         }
    }

I cannot remember why this worked, remembered after I made the post, but its something to do with long term SSL connections and WSSharp

PaulGWebster avatar Jan 25 '21 09:01 PaulGWebster

We use this in a small desktop app that communicates with a web application (angular). Most of the time it works well, but sometimes it gets very unstable and throws the same error you posted. "The header of a frame cannot be read from the stream.".

We mostly see this when the mentioned web application has a successful connection and the user just refreshes the page (F5). Then the connection gets in a "connect-disconnect" loop with the above error. Frequency of the error has increased when we started using SSL.

@sta Do you have any pointers on how we can deal with this or at least how we can pinpoint the issue? I've seen way to many posts about this.

manijak avatar Jan 26 '21 12:01 manijak

Have you guys manage to make this work? I'm having a problem right now when connecting websocketsharp to NGINX. Keep getting this error: AM|Fatal|WebSocket.Connect|WebSocketSharp.WebSocketException: The proxy has failed a connection to the requested host and port.

Tried to enable the proxy:

 using (var ws = new WebSocket("ws://localhost:1234/mylocalnginx")) // My backend host
            {
                ws.SetProxy("http://localhost:5556", null, null); // My nginx
                ws.OnMessage += (sender, e) => {
                    Debug.WriteLine("Received a message: " + e.Data);
                };

darkmakukudo avatar May 21 '21 17:05 darkmakukudo

@darkmakukudo In my case it was a docker from windows. Since windows run ubuntu dockers on WSL, it create a different network, so I had to use host.docker.internal instead of localhost.

https://docs.docker.com/desktop/features/networking/#i-want-to-connect-from-a-container-to-a-service-on-the-host

eyalpd-lmt avatar Jun 04 '25 05:06 eyalpd-lmt