Chuyển đến nội dung

Bài 34 · Projects and Practice

Project: a chat room with processes

Build a chat room in Erlang from processes and messages: a room server, join and leave, broadcast, monitoring clients, and a runnable JavaScript model of the design.

In this project you build a chat room the Erlang way: one process per participant and one process for the room. You will use everything from this chapter: spawn, !, receive, state in a loop, monitors and (at the end) a supervisor. First you design on paper, then read the Erlang code, then run a faithful JavaScript model of it in the browser (Erlang cannot run on this site).

Requirements

  • A room keeps the list of members.
  • A client can join(Room, Name), say(Room, Text) and leave(Room).
  • Every message is broadcast to all members except the sender.
  • If a client process crashes, the room must remove it automatically.
  • Nothing should block: the room never waits for a slow client.

Design

flowchart LR
    A["client Ada"] -- "say" --> R(("room"))
    B["client Bob"] -- "join" --> R
    R -- "{msg, Ada, Text}" --> B
    R -- "{msg, Ada, Text}" --> C["client Cy"]
    R -. "monitor" .-> A
    R -. "monitor" .-> B
    R -. "monitor" .-> C

The room monitors every member and broadcasts messages by sending to their pids.

The room's state is a map from pid to name. The messages the room understands are the protocol:

Message Meaning
{join, Pid, Name} add a member, monitor it, announce it
{say, Pid, Text} broadcast {msg, Name, Text} to the others
{leave, Pid} remove a member, stop monitoring
{'DOWN', Ref, process, Pid, _} member died: remove it

The room

ERLANG
-module(chat_room).
-export([start/0, join/2, say/2, leave/1]).

start() ->
    spawn(fun() -> loop(#{}) end).

join(Room, Name) -> Room ! {join, self(), Name}, ok.
say(Room, Text)  -> Room ! {say, self(), Text},  ok.
leave(Room)      -> Room ! {leave, self()},      ok.

loop(Members) ->
    receive
        {join, Pid, Name} ->
            Ref = erlang:monitor(process, Pid),
            broadcast(Members, {joined, Name}),
            loop(Members#{Pid => {Name, Ref}});
        {say, Pid, Text} ->
            case Members of
                #{Pid := {Name, _}} -> broadcast(maps:remove(Pid, Members), {msg, Name, Text});
                _ -> ok                                   % ignore strangers
            end,
            loop(Members);
        {leave, Pid} ->
            loop(remove(Pid, Members));
        {'DOWN', _Ref, process, Pid, _Reason} ->
            loop(remove(Pid, Members));
        _Other ->
            loop(Members)
    end.

broadcast(Members, Message) ->
    maps:foreach(fun(Pid, _) -> Pid ! Message end, Members).

remove(Pid, Members) ->
    case maps:take(Pid, Members) of
        {{Name, Ref}, Rest} ->
            erlang:demonitor(Ref, [flush]),
            broadcast(Rest, {left, Name}),
            Rest;
        error ->
            Members
    end.

Points to notice:

  • #{Pid := {Name, _}} in a pattern matches only when Pid is a key: it checks membership and extracts the name in one step.
  • maps:take/2 returns {Value, RestOfMap} or error, handy for removals.
  • maps:foreach/2 (OTP 24+) runs a fun for its side effect.
  • demonitor(Ref, [flush]) guarantees no stale DOWN message is left behind.
  • broadcast uses !, which never blocks, so a slow or dead client cannot stall the room.

A client

A client is any process that receives the room's messages. A minimal one prints them:

ERLANG
client(Room, Name) ->
    spawn(fun() ->
        chat_room:join(Room, Name),
        client_loop(Name)
    end).

client_loop(Name) ->
    receive
        {msg, From, Text} -> io:format("[~s sees] ~s: ~s~n", [Name, From, Text]), client_loop(Name);
        {joined, Who}     -> io:format("[~s sees] ~s joined~n", [Name, Who]), client_loop(Name);
        {left, Who}       -> io:format("[~s sees] ~s left~n", [Name, Who]), client_loop(Name);
        stop              -> ok
    end.

Run the model

The JavaScript below mirrors the Erlang code line by line, with the same protocol and the same state. It is a stand-in, not Erlang: processes become objects with a mailbox, and the scheduler runs one message at a time. The crashing client triggers the monitor logic.

JS Stand-in: the chat room

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check the output: Ada's message reaches Bob and Cy but not Ada; after Bob's crash, Ada and Cy are told he left, and later messages are no longer sent to him.

Make it supervised

Run the room under a supervisor so that if the room itself crashes it comes back (members will have to rejoin, or you can add a registry later). Register it by name so clients do not need the pid:

ERLANG
%% in chat_room.erl
start_link() ->
    Pid = spawn_link(fun() -> loop(#{}) end),
    register(chat_room, Pid),
    {ok, Pid}.

Add a child spec #{id => chat_room, start => {chat_room, start_link, []}} to a supervisor as in supervisors, and clients now call chat_room ! {join, self(), Name}. For production, the room would be a gen_server with a pg group for members across several nodes (distributed nodes).

Extensions to try

  1. Private messages: {whisper, Pid, ToName, Text} looks up a name and sends only to it.
  2. A history: keep the last 20 messages in the state and send them to a new member on join.
  3. Rate limiting: count messages per member in the state and drop excess.
  4. Multiple rooms: a room manager that creates a room process per name.
  5. TCP front end: accept gen_tcp connections and run a client process per socket (ports and sockets).

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why does the room monitor each member?

    The DOWN message tells the room that a member crashed, so it can clean up and tell the others.
  2. 2. Why can a slow client not block the room?

    Messages are queued in the client's mailbox; the room continues immediately.
  3. 3. What does the pattern #{Pid := {Name, _}} do in the say clause?

    A map pattern with := matches an existing key and binds the value.
  4. 4. How could the room survive its own crash?

    A supervisor restarts the process and the registered name points to the new one.

Summary

  • One process per participant plus one room process gives a simple, scalable design.
  • The room's protocol is a handful of messages; its state is a map in a tail-recursive loop.
  • Monitors make clean-up automatic; asynchronous sends keep the room responsive.
  • Supervising and naming the room, then moving it to gen_server, are the natural next steps.

Next: Project: a supervised key-value store

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.