How does one go about sending a message from a Jinterface Java server to a globally registered gen_server?
For example, my gen_server was started like this:
start_link ({global, myServerName}, Mod, Args, Options).
mbox.send("myServerName", MyMessage). doesn't work. No message arrives at myServerName:handle_info.
One way is to invoke
global:send/2
as an RPC on the server node. The Java code would look like this:The second argument to the
OtpSelf
constructor is the Erlang cookie, which has to match the cookie of the server node as we'll see below. The code uses thesendRPC
method ofOtpConnection
to call theglobal:send/2
function on the server node, which returns the pid of the globally-registered process if it succeeds or an error if not (but the Java code doesn't check this).The server could be a simple
gen_server
and look like this:Note that I register the server with the global name
myServerName
to match what you used in your question, but in practice I never use mixed-case atom names like that.To run the server, first start an Erlang shell:
Note that the cookie matches what's in the Java code, and also that I used
-sname
to name the server node; I didn't try long names at all.Then, run the
svr
process in the Erlang shell:Then, run the Java client, and the server should emit the following message:
The main drawback to this approach is that it has to go through the RPC server for each message. Another alternative would be to send an RPC to
global:whereis_name/1
to look up the pid of the registered process, and then send messages directly to it usingsend
instead ofsendRPC
, but the drawback there is that if the globally-registered process dies and is restarted, the Java code will need to detect that the pid is no longer valid and redo the lookup.