Étude 11-4: Chat Room
In the previous études, the client simply made a call to the server, and didn’t do any processing of its own. In this étude, you will create a “chat room” with a chat server and multiple clients, much as you see in Server with multiple clients.
Server with multiple clients.
The interesting part of this program is that the client will also be
a gen_server
, as shown in Client as a gen_server.
Client as a gen_server
.
Up until now, you have been using a module name as the first argument to
gen_server:call/2
, and in the previous étude, you used
net_adm:ping/1
to connect to a server.
In this étude, you won’t need net_adm:ping/1
. Instead,
you will use a tuple of the form
{Module, Node}
to directly connect to the node you want. So, for
example, if you want to make a call to a module named chatroom
on
a node named lobby@localhost
, you would do something like this:
gen_server:call({chatroom, lobby@localhost}, Request)
This means
you won’t need to connect with net_adm:ping/1
.
Here is my design for the solution. You, of course, may come up with an entirely different and better design.
My solution has two modules, both of which use the gen_server
behavior.
The chatroom
Module
The first module, chatroom
, will keep as its state a list of tuples, one tuple for each person in the chat. ...
Get Études for Erlang now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.