1

誰かがこの単純な分散型 erlang の例を手伝ってくれませんか? この erlang プログラムを実行して、その動作を確認するにはどうすればよいですか? 私は、erl -sname pc1、erl -sname pc2、erl -sname server で 3 つのシェルを見つめました。また、pc1 と pc2 サーバーから 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.
4

1 に答える 1

1

これをお勧めします: http://www.erlang.org/doc/getting_started/conc_prog.html

とにかく、すべてのノードが同じ Cookie を共有している場合、3 つの異なるシェルを開始します。

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

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

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

n1 で次のことを行います。

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

n3で次のことを行います:

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

n1 では、次を取得する必要があります。

Received message news1 for topic football

もちろん、必要に応じて拡張することもできます。

于 2012-04-12T11:04:36.590 に答える