Skip to content

Instantly share code, notes, and snippets.

@bluegraybox
Created January 18, 2012 02:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bluegraybox/1630442 to your computer and use it in GitHub Desktop.
Save bluegraybox/1630442 to your computer and use it in GitHub Desktop.
Simple publish-subscribe service (for erlangdc)
-module(pubsub).
-export([handle/0, server/0]).
server() ->
register(ps, handle()).
%% handle/0
handle() ->
spawn(fun () -> handle([]) end).
%% handle/1
handle(Subscribers) ->
receive
{subscribe, Pid} ->
io:format("Pid=~p subcribed!~n", [Pid]),
handle([Pid|Subscribers]);
{unsubscribe, Pid} ->
io:format("Pid=~p unsubcribed!~n", [Pid]),
handle(lists:delete(Pid, Subscribers));
{message, Message} ->
sendMessage(Message, Subscribers),
handle(Subscribers);
Unknown ->
io:format("Unknown message: ~p~n", [Unknown]),
handle(Subscribers)
end.
sendMessage(_Message, []) -> ok;
sendMessage(Message, [First|Rest]) ->
First ! Message,
sendMessage(Message, Rest).
@bluegraybox
Copy link
Author

Start it up in one Erlang VM, named 'foo'. It registers the service as 'ps':

colin@Anna:~/Development/pubsub$ erl -sname foo
Erlang R14B03 (erts-5.8.4) [source] [smp:2:2] [rq:2] [async-threads:0] [kernel-poll:false]

Eshell V5.8.4  (abort with ^G)
(foo@Anna)1> pubsub:server().
true
(foo@Anna)2> ps ! {subscribe, self()}.
Pid=<0.38.0> subcribed!
{subscribe,<0.38.0>}

Start up another VM ('bar') and connect it to 'foo':

colin@Anna:~/Development/pubsub$ erl -sname bar
Erlang R14B03 (erts-5.8.4) [source] [smp:2:2] [rq:2] [async-threads:0] [kernel-poll:false]

Eshell V5.8.4  (abort with ^G)
(bar@Anna)1> node().
bar@Anna
(bar@Anna)2> nodes().
[]
(bar@Anna)3> net_adm:ping(foo@Anna).
pong
(bar@Anna)4> nodes().               
[foo@Anna]

Then send a message from 'bar':

(bar@Anna)5> Ps = {ps, foo@Anna}.
{ps,foo@Anna}
(bar@Anna)6> Ps ! {message, "test remote"}.
{message,"test remote"}

And receive it at 'foo':

(foo@Anna)3> flush().
Shell got "test remote"
ok

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment