[erlang-questions] Stateful gen_servers

David Terrell <>
Wed Oct 10 16:39:42 CEST 2007


On Sat, Oct 06, 2007 at 06:45:17PM -0700, David King wrote:
> > I would like to use gen_server to develop a stateful server, and  
> > since gen_servers are  generally communicated using module:function 
> > (arg) syntax, what's the best way to use them as stateful servers  
> > per client, i.e., each for each client a gen_server is started and  
> > is terminated when client asks explicitly or when client is  
> > terminated. Thanks.
> 
> You could have each client do something like:
> 
> Session=my_server:logon(),
> Cookie=my_server:get_cookie(Session),
> my_server:eat_cookie(Session,Cookie), [...]
> 
> Then in the server, the State field could have a dict of Sessions  
> (generated via make_ref()?) to state information
> 
> If that's not enough, I have a tictactoe server that I wrote recently  
> that maintains the states of games this way, so let me know if you  
> want some live code that does this

What I've done for situations like this is have logon() call 
spawn_link(), without a registered name, and then do something
like:

get_cookie(Session) -> gen_server:call(Session, get_cookie).

Ideally the new gen_server would be added to a supervisor, not
spawned directly, but then call link() so that it shuts down
if the client pid exits.

-- 
David Terrell

((meatspace)) http://meat.net/



More information about the erlang-questions mailing list