Cloudflare Worker Websocket

This is websocket code that handle a "Controller" and "MCU". ( Assume that controller and device are two different devices that makes two different connections with cf worker websocket) when client send register1 or register2 worker register connection as Controller and MCU respectively. When normal message sent by MCU or Controller in format "message-<message here>" it checks who sent it and forward it to opposite one. But there is problem in code. the registration works well. But normal messaging not delivered to both devices ( MCU and Controller and vise versa). Can anyone help me to figure the problem out. Here is my code : https://pastebin.com/raw/h17weWxa
2 Replies
DaniFoldi
DaniFoldi7mo ago
Hi @verifieduser, It may be that the two connections are reaching different worker instances. Cloudflare Workers run on every server worldwide (thousands), and your code doesn't share state with others. In my opinion the best solution for you would be to use Durable Objects (requires Workers paid plan, and a tiny refactor to module syntax workers), and I recommend the WebSocket Hibernation API so you don't pay for "idle time". Ref: https://developers.cloudflare.com/durable-objects and https://developers.cloudflare.com/durable-objects/api/websockets/ Basically, Durable Objects would solve your problem of having multiple workers, since you could connect all devices to a single DO (guaranteed to be unique by id). You can keep your websockets in memory or have the DO hibernate (see examples in the docs). Also, I found a small logical bug in the code you posted, connected clients that don't send register 1 or 2 are defaulted to MCU, but are never added to the set so they'll never receive anything back from controllers. I hope this helps MeowHeartCloudflare
VerifiedUser - X
Thank you for the reply. I will try using CF DO. 👍