Created
January 18, 2012 02:22
-
-
Save bluegraybox/1630442 to your computer and use it in GitHub Desktop.
Simple publish-subscribe service (for erlangdc)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Start it up in one Erlang VM, named 'foo'. It registers the service as 'ps':
Start up another VM ('bar') and connect it to 'foo':
Then send a message from 'bar':
And receive it at 'foo':