What OTP pattern to use for gen

So I have a non- blocking OTP socket server very similar to the one in Learn Yorself Some Erlang:

http://learnyousomeerlang.com/buckets-of-sockets

The supervisor passes the listening socket to dynamically spawned gen_servers, each of which can accept a single connection; in this way the listening socket isn't blocked by (blocking) calls to gen_tcp:accept, and each gen_server spawned by the supervisor effectively represents a single client.

Now this is all very nice and I can talk to the server via telnet, a simple echo handler echoing my requests.

But what if I want to extend this into a simple chat server ? Obvious thing missing here is the ability to send a broadcast message to all connected clients. But currently none of the gen_server clients know about the existence of any of the others!

What's a sensible OTP- compliant pattern for one gen_server to be able to get pids for all the others ? Only way I can think of is to have some kind of mnesia/ets table containing pids/usernames as part of the gen_server state variable, but somehow this doesn't seem very OTP- like.

Thoughts ?

Thanks in advance.


Using an ETS table to store the Pids would be the way to go. I would use a supervised process as the table manager and set up monitors on Pids that are added to the ETS table, that way you can detect when a process dies and can remove it from the ETS table.

For fault tolerance when working with ETS you need to take some precautions, see Don't Loose your ets Tables for a good intro on how to do this.

But for a real system I would use either the pg2 or gproc modules doing this kind of stuff. pg2 is included in OTP and geared more towards distributed systems, gproc is more flexible. Both use ETS tables to store the data.

链接地址: http://www.djcxy.com/p/38188.html

上一篇: Erlang:如何处理长时间运行的init回调?

下一篇: gen用什么OTP模式