Reputation: 5093
I have a gen_server
(my_gen_server.erl
) that is started by another server (i.e. ejabberd
)
Inside my_gen_server.erl
, I start another server which handles HTTP2
calls like this:
{ok, ServerPid} = apns:connect(cert, my_first_connection).
Now, my_gen_server
is receiving messages both from ejabberd
and ServerPid
which I handle as follows:
1. handle_info({reconnecting, ServerPid}=Msg, State) -> %% do Something
2. handle_info({connection_up, ServerPid}=Msg, State) -> %% do Something
3. handle_info(#offline_msg{...} = _Msg, State) -> %% do Something
So 1 & 2 are sent by ServerPid
and 3 is sent by ejabberd
. This is working but I am not sure about the correct behavior. So,
My question is:
gen_server
behavior to receive/handle messages from multiple client processes?Please help.
Upvotes: 1
Views: 217
Reputation: 48589
Any process that has the gen_server's pid can send the gen_server a message using !
, which will be handled by the gen_server's function:
handl_info()
Any process that has the gen_server's pid can call the functions:
call(GenServerPid, Msg)
cast(GenServerPid, Msg)
which will be handled by the gen_server functions:
handle_call()
handle_cast()
In elixir, there is a module called Agent
, which is just a gen_server that stores State, like a counter. Multiple processes can update the counter and retrieve the current count. Of course, some process has to start the gen_server, then pass the pid to the other processes that want to update/retrieve the count.
Upvotes: 3