0 Replies - 4468 Views - Last Post: 11 April 2012 - 12:55 AM

#1 sromic  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 11-April 12

please help me to run erlang example

Posted 11 April 2012 - 12:55 AM

can someone help me with this simple distributed erlang exampe. How can i run this erlang program to see how it works? i have stared 3 shells with erl -sname pc1, erl -sname pc2 and erl -sname server and aslo i ping from pc1 and pc2 server to make connection between them. now what else i need to do so i could test this program?
-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.


This post has been edited by macosxnerd101: 12 April 2012 - 06:59 AM
Reason for edit:: Added code tags and moved to Functional Programming


Is This A Good Question/Topic? 0
  • +

Page 1 of 1