How to send a message to a web-socket callback module in yaws/Erlang

312 views Asked by At

How do I send a message to a handle_message callback function of a web-socket callback module to update its InternalState from another web-socket callback module??

2

There are 2 answers

0
Steve Vinoski On

If you want Yaws websocket callback processes to know about other such processes, you'll have to create some sort of registry yourself. Yaws websocket processes are unregistered because Yaws has no need to find them; each is associated with a socket, and activity on their respective sockets is how their messages get to them.

One way to implement such a registry would be to have the websocket callback module init function call erlang:register/2, but that approach suffers from the problem of needing a new atom name for each callback process, and if your server runs long enough you'll run out of atoms and crash the Erlang VM.

A better approach is to create a gen_server registry process that manages an ets table, and then have the websocket callback module init function register itself with that process, which would then store the details into the ets table. A callback process could find another one either by accessing the ets table directly (assuming it allows public reads), or by calling a query function on the registry process, though note that in the latter case if such calls are frequent and there are lots of websocket processes, the registry could be a bottleneck.

The second approach allows you to use keys other than atoms, such as strings, integers, or binaries, and so it doesn't suffer from the problem of running out of atoms. Another benefit is that the registry process can monitor each registered websocket callback process and remove them from the registry when they die.

If you're not using Yaws in embedded mode, you could use the yapps feature of Yaws to start an application of your own, running co-located with Yaws, to start a supervisor that then starts and manages the registry process. In this case, there's no need to register the yapp with each virtual server as the docs suggest, since the yapp itself wouldn't be handling Yaws requests.

0
chengweichao On

I have a similar approach. If you have more than one Yaws server to handle websocket, you can store the websocket Pid to mnesia, and use Pid ! Message to send message to specific websocket Pid, finally the websocket callback module handle_info/2 will be called.