Pass Data between two Nodes erlang

Viewed 23

I have recently started learning Erlang and I am trying to implement a server-client sample program. I have created a registered process and I would like to send data to it from another process. The code is as follows.

-module(mine).
-export([alice/0, bob/2, startAlice/0, startBob/1]).

alice() ->
    receive
        {message, BobNode} ->
            io:fwrite("Alice got a message \n"),
            BobNode ! message,
            alice()
        finished -> io:fwrite("Alice is finished\n")
    end.

bob(0, AliceNode) ->
    {alice, AliceNode} ! finished,
    io:fwrite("Bob is finished\n");

bob(N, AliceNode) ->
    {alice, AliceNode} ! {message, self()},
    receive
        message -> io:fwrite("Bob got a message ~w \n",[N])
    end,
    bob(N-1, AliceNode).

startAlice() ->
    register(alice, spawn(mine, alice, [])).

startBob(AliceNode) ->
    spawn(mine, bob, [30000, AliceNode]).

Here, I would like to send some value say N, from bob to alice. I tried sending the data as

{alice, AliceNode, Nvalue} ! {message, self(), N} in bob(N, AliceNode) function, but got the error variable 'Nvalue' is unbound erl. I am sure I am missing something trivial here. Any help would be appreciated. Thanks in advance.

1 Answers

Since you register the Alice-process with the name alice, all you need to do to send a message to said process is to send it to the registered name, i.e.:

alice ! {message, self()}

If you also want to send some value, say N, besides the atom message and Bob's Pid, you will want to receive such message on Alice's end by adding a clause in the receive statement of alice/0, e.g.:

{message, BobNode, N} ->
            io:format("Alice got a message with value: ~w~n", [N]),
            BobNode ! message,
            alice();

For what it's worth, the error message you saw implies that Nvalue is not bound, i.e. you hadn't bound it to something: Nvalue = something. Not sure what value you wanted it to be in the first place though.

Related