如何运行这个Erlang示例?

wkftcu5l  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(160)

有人能帮我这个简单的分布式erlang exampe。我如何运行这个erlang程序,看看它是如何工作的?我已经启动了3个shell与erl -sname pc 1,erl -sname pc 2和erl -sname服务器,并从pc 1和pc 2服务器ping使它们之间的连接。现在我还需要做什么,所以我可以测试这个程序?

-module(pubsub2).
-export([startDispatcher/0, startClient/0, 
     subscribe/2, publish/3]).

startClient() ->
    Pid = spawn(fun clientLoop/0),
    register(client, Pid).

clientLoop() ->
    receive {Topic, Message} ->
        io:fwrite("Received message ~w for topic ~w~n",
              [Message, Topic]),
        clientLoop()
    end.

subscribe(Host, Topic) ->
    {dispatcher, Host} ! {subscribe, node(), Topic}.

publish(Host, Topic, Message) ->
    {dispatcher, Host} ! {publish, Topic, Message}.

startDispatcher() ->
    Pid = spawn(fun dispatcherLoop/0),
    register(dispatcher, Pid).

dispatcherLoop() -> 
    io:fwrite("Dispatcher started\n"),
    dispatcherLoop([]).
dispatcherLoop(Interests) ->
    receive
    {subscribe, Client, Topic} ->
        dispatcherLoop(addInterest(Interests, Client, Topic));
    {publish, Topic, Message} ->
        Destinations = computeDestinations(Topic, Interests),
        send(Topic, Message, Destinations),
        dispatcherLoop(Interests)
    end.

computeDestinations(_, []) -> [];
computeDestinations(Topic, [{SelectedTopic, Clients}|T]) ->
    if SelectedTopic == Topic -> Clients;
       SelectedTopic =/= Topic -> computeDestinations(Topic, T)
    end.

send(_, _, []) -> ok;
send(Topic, Message, [Client|T]) ->
    {client, Client} ! {Topic, Message},
    send(Topic, Message, T).

addInterest(Interests, Client, Topic) ->
    addInterest(Interests, Client, Topic, []).
addInterest([], Client, Topic, Result) ->
    Result ++ [{Topic, [Client]}];
addInterest([{SelectedTopic, Clients}|T], Client, Topic, Result) ->
    if SelectedTopic == Topic ->
        NewClients = Clients ++ [Client],
        Result ++ [{Topic, NewClients}] ++ T;
       SelectedTopic =/= Topic ->
        addInterest(T, Client, Topic, Result ++ [{SelectedTopic, Clients}])
    end.
oprakyz7

oprakyz71#

I suggest you this: http://www.erlang.org/doc/getting_started/conc_prog.html
Anyhow, given that you all nodes share the same cookie, start 3 different shells

erl -sname n1
(n1@ubuntu)1> pubsub2:startClient().

erl -sname n2
(n1@ubuntu)1> pubsub2:startDispatcher().

erl -sname n3
(n1@ubuntu)1> pubsub2:startClient().

in n1 do:

(n1@ubuntu)1> pubsub2:startClient().
(n1@ubuntu)2> pubsub2:subscribe('n2@ubuntu', football).

in n3 do:

(n3@ubuntu)1> pubsub2:startClient(). 
(n3@ubuntu)1> pubsub2:publish('n2@ubuntu', football, news1).

in n1 you should get:

Received message news1 for topic football

Of course, you can expand it as you wish.

相关问题