Skip to content

initiate ws session

Serge edited this page Oct 1, 2021 · 2 revisions

When the websocket session request arrived, we are asking Mochiweb to upgrade connection to a websocket one:

route(Request) ->
    {ReentryWs, ReplyChannel} = mochiweb_websocket:upgrade_connection(
                                    Request, fun ?MODULE:ws_request_handler/3),

We are providing a callback function ws_request_handler/3 which will serve the websocket sequests during the session lifespan. Mochiweb gives us

  • a ReentryWS function, which is effectively a loop process calling the callback we provided;
  • a ReplyChannel function which we pass our websocket responses to - to send them back to the browser.
    Path = list_to_binary(mochiweb_request:get(path,Request)),
    <<"/websocket/",Modstr/binary>> = Path,
    Mod = binary_to_existing_atom(Modstr),
    {_Status, Server, All} = Mod:start([]),
    ok = client_keeper:subscribe({Mod, Server, ReplyChannel}),
    Mod:reply(All, ReplyChannel),
    ReentryWs(self()).