Question

I have an Erlang websocket server developed with Cowboy.

I would like to keep a state variable for each connection, which depends on the commands sent by the client.

Which is the best way to persist a state variable for each websocket connection?

EDIT: with "persist" I mean it should be kept in memory only for the lifetime of the connection, no need for a database.

Was it helpful?

Solution

All the websocket functions take a user-defined State argument used for keeping your own state between function calls. The state is discarded when the websocket is closed.

You initialize it in the return value of websocket_init/3, websocket_handle/3 and websocket_info/3 takes the state as argument where you can lookup the data you need. In the return value of websocket_init/3 and websocket_handle/3 you pass on the new state (or the same if no state update was needed). A sketch:

websocket_init(_TransportName, Req, _Opts) ->
     MyInitialState=just_started, % The state can be any erlang term,e.g. a record
     {ok, Req, MyInitialState}.

websocket_handle({text, _Msg}, Req, State) ->
     NewState = case State of
            just_started -> up_and_running;
            _ -> still_running
          end,
     {ok, Req, NewState}.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top