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/2as an RPC on the server node. The Java code would look like this:The second argument to the
OtpSelfconstructor is the Erlang cookie, which has to match the cookie of the server node as we'll see below. The code uses thesendRPCmethod ofOtpConnectionto call theglobal:send/2function 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_serverand look like this:Note that I register the server with the global name
myServerNameto 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
-snameto name the server node; I didn't try long names at all.Then, run the
svrprocess 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/1to look up the pid of the registered process, and then send messages directly to it usingsendinstead 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.