【问题标题】:How to run this Erlang example?如何运行这个 Erlang 示例?
【发布时间】:2021-01-31 04:24:18
【问题描述】:

有人可以帮助我完成这个简单的分布式 erlang 示例吗?我如何运行这个 erlang 程序来查看它是如何工作的? 我用 erl -sname pc1、erl -sname pc2 和 erl -sname server 盯着 3 个 shell 我还从 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.

【问题讨论】:

    标签: erlang


    【解决方案1】:

    我建议你这样做:http://www.erlang.org/doc/getting_started/conc_prog.html

    无论如何,假设所有节点共享相同的 cookie,启动 3 个不同的 shell

    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-07-16
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 2014-12-19
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 2013-02-06
      相关资源
      最近更新 更多