First create an EchoServer in Java that receives messages in the format {Sender,Data} and echoes the Data portion back to the Sender. You will need OtpErlang.jar in your build classpath and runtime classpath. I found it in /opt/local/lib/erlang/lib/jinterface-1.5.1/priv/ on Mac OS X. I had to install Erlang from source on Ubuntu since the APT package is missing Jinterface.
Listing for EchoServer.java:
import com.ericsson.otp.erlang.*;
public class EchoServer {
public static void main(String[] args) throws Exception {
OtpNode node = new OtpNode("java");
OtpMbox mbox = node.createMbox("echo");
OtpErlangAtom SHUTDOWN = new OtpErlangAtom("shutdown");
while (true) {
OtpErlangObject message = mbox.receive();
System.out.format("%s received: %s%n", mbox.self(), message);
if (SHUTDOWN.equals(message)) {
System.out.format("%s shutting down...%n", mbox.self());
break;
} else if (message instanceof OtpErlangTuple) {
OtpErlangTuple messageTuple = (OtpErlangTuple) message;
if (messageTuple.arity() == 2 && messageTuple.elementAt(0) instanceof OtpErlangPid) {
OtpErlangPid sender = (OtpErlangPid) messageTuple.elementAt(0);
OtpErlangObject sendersMessage = messageTuple.elementAt(1);
mbox.send(sender, sendersMessage);
}
}
}
}
}
Once you have compiled and started the EchoServer you can communicate with it from the Erlang shell. First you need to start a new named node with erl -sname erl_node.
Listing of the Erlang shell interaction:
Erlang R13B01 (erts-5.7.2) [source] [64-bit] [smp:4:4] [rq:4] [async-threads:0] [hipe] [kernel-poll:false]
Eshell V5.7.2 (abort with ^G)
(erl_node@alains_desktop)1> net_adm:ping(java@alains_desktop).
pong
(erl_node@alains_desktop)2> {echo,java@alains_desktop} ! {self(),"Hello, Java!"}.
{<0.39.0>,"Hello, Java!"}
(erl_node@alains_desktop)3> % use f(M) to "forget" M (make it unbound)
(erl_node@alains_desktop)3> f(M), receive M -> {ok,M} after 100 -> {error,timeout} end.
{ok,"Hello, Java!"}
(erl_node@alains_desktop)4> {echo,java@alains_desktop} ! {self(),{tuples,can,be,sent,too}}.
{<0.39.0>,{tuples,can,be,sent,too}}
(erl_node@alains_desktop)5> f(M), receive M -> {ok,M} after 100 -> {error,timeout} end.
{ok,{tuples,can,be,sent,too}}
(erl_node@alains_desktop)6> {echo,java@alains_desktop} ! shutdown.
(erl_node@alains_desktop)6>
(erl_node@alains_desktop)7> {echo,java@alains_desktop} ! shutdown.
shutdown
(erl_node@alains_desktop)8> {echo,java@alains_desktop} ! {self(),"Are you there?"}.
{<0.39.0>,"Are you there?"}
(erl_node@alains_desktop)9> f(),receive M -> {ok,M} after 100 -> {error,timeout} end.
{error,timeout}
(erl_node@alains_desktop)10>
Listing of EchoServer Java process output:
#Pidreceived: {#Pid ,"Hello, Java!"} #Pid received: {#Pid ,{tuples,can,be,sent,too}} #Pid received: shutdown #Pid shutting down...
No comments:
Post a Comment