I would like to build a dynamic web app, and i’ve found sockjs very promising.
However, i can’t figure how to push data from the server to the client. The documentation (wich consists in two tiny examples) show some « echo server » examples.
But what i would get is :
- The user opens a connection with sockjs then i get a PID or an id
- Then i can send messages to this pid to push to the browser
I don’t know what to do.
This is their handler
service_echo(_Conn, init, state) -> {ok, state};
service_echo(Conn, {recv, Data}, state) -> Conn:send(Data);
service_echo(_Conn, closed, state) -> {ok, state}.
I would like something like this
service_push(Conn, init, state) ->
Pid = Conn:pid(),
---- here get user ID from cookies or another way ----
push_service:register(user,UserID,Pid),
{ok, state};
service_echo(Conn, {recv, Data}, state) -> do_something:with(Data);
service_echo(Conn, closed, state) -> service_push:unregister(Conn:pid()).
And then i could send infos to the Conn’s Pid and this Conn would send data to the client.
I don’t know how to write.
Thanks
Well, pid is hidden under ‘Conn’ record. Just pass ‘Conn’ around. Whenever you want to send something, call ‘Conn:send(Data)’, that’s it.
In this model you obviously can still pass around Conn even if the connection is closed. In order to do it “properly” you could create a gen_server every time a connection is created and encapsulate Conn there. That way your code will be responsible for passing data between your app and sockjs.
Here is my code that does exactly that (but for a more complex project):
https://github.com/rabbitmq/rabbitmq-web-stomp/blob/master/src/rabbit_ws_sockjs.erl#L56