-
Notifications
You must be signed in to change notification settings - Fork 3
/
message_router.erl
53 lines (45 loc) · 1.58 KB
/
message_router.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
-module(message_router).
-define(SERVER, message_router).
-compile(export_all).
start() ->
server_util:start(?SERVER, {message_router, route_messages, [dict:new()]}),
message_store:start().
stop() ->
server_util:stop(?SERVER),
message_store:stop().
send_chat_message(Addressee, MessageBody) ->
global:send(?SERVER, {send_chat_msg, Addressee, MessageBody}).
register_nick(ClientName, ClientPid) ->
global:send(?SERVER, {register_nick, ClientName, ClientPid}).
unregister_nick(ClientName) ->
global:send(?SERVER, {unregister_nick, ClientName}).
route_messages(Clients) ->
receive
{send_chat_msg, ClientName, MessageBody} ->
case dict:find(ClientName, Clients) of
{ok, ClientPid} ->
ClientPid ! {printmsg, MessageBody};
error ->
message_store:save_message(ClientName, MessageBody),
io:format("Archived messages for ~p~n", [ClientName])
end,
route_messages(Clients);
{register_nick, ClientName, ClientPid} ->
Messages = message_store:find_messages(ClientName),
lists:foreach(fun(Msg) -> ClientPid ! {printmsg, Msg} end, Messages),
route_messages(dict:store(ClientName, ClientPid, Clients));
{unregister_nick, ClientName} ->
case dict:find(ClientName, Clients) of
{ok, ClientPid} ->
ClientPid ! stop,
route_messages(dict:erase(ClientName, Clients));
error ->
io:format("Error! Unknown client: ~p~n", [ClientName]),
route_messages(Clients)
end;
shutdown ->
io:format("Shutting down~n");
Oops ->
io:format("Warning! Received: ~p~n", [Oops]),
route_messages(Clients)
end.