Reputation: 41
I’m working on a web app with a Python Flask backend that uses Flask-SocketIO for WebSocket connections, and the frontend client is built with React using the socket.io-client library. Everything works perfectly in local development, but once I deploy the app to their respective Google Cloud Run services, I encounter a problem where the Socket client successfully connects, but immediately begins to disconnect and reconnect every couple seconds in a continuous loop.
I have this code in my client to print the Socket.io-client details for disconnecting each time:
socketio.on('disconnect', (reason, details) => {
console.log('Disconnected', reason);
console.log(details.message);
console.log(details.description);
console.log(details.context);
})
This produces these error messages:
Disconnected transport error
xhr post error
400
XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}
I also see these errors in my console which seem like they're side effects of the websocket disconnecting.
WebSocket connection to '<URL>' failed: WebSocket is closed before the connection is established.
GET https:/backendurl/socket.io/?EIO=4&transport=polling&t=P88aKpu&sid=Iu5r6Lfn-b0Uh4ISAAD8 400 (Bad Request)
While these disconnections are going on, I am unable to communicate over the websocket. This lasts for maybe 20 seconds (or around 10 disconnection iterations) then stops, then I can resume using the websocket and the rest of my app as normal. The weird part is that this lasts for a varying amount of time depending on when I interact with my server. Sometimes, this problem doesn't happen at all when I connect to the websocket, sometimes it only disconnects brielfy once or twice, then other times, the disconnections lasts a very long time. It all seems very random when I try to replicate the bug.
I've included snippets of my network tab, one for when I have the issue and the other for when I don't. I believe the pending status 101 requests indicate that the disconnections have finally stopped and the websocket is open.
Would greatly appreciate any help fixing this issue.
In the snippet below, the websocket is set up smoothly.
Upvotes: 0
Views: 598
Reputation: 41
A default SocketIO client begins by first establishing an HTTP long-polling transport to the server. The errors I was seeing were somehow introduced during this process, indicated by xhr post error
in the error messges. I fixed the issue by simply changing the client to forgo the initial HTTP polling mechanism and directly connect to the server with Websocket transport.
const socket = io(server_url, {transports: ['websocket']})
The relevant documentation can be found at https://socket.io/docs/v3/client-initialization/#transports
Upvotes: 0