Web Sockets! The new kid in town! Joe loves it, maybe you should too?
Web Sockets allow for *real* two-way communication between the browser and Yaws without the overhead and latency that come with polling/long-polling solutions. That should be enough for an introduction. Now... how to use it?
First start by returning:
{websocket, CallbackMod, Options}from the out/1 function, where CallbackMod is an atom identifying your Websocket callback module, and Options can be an empty list. This makes the erlang process within yaws processing that particular page do a protocol upgrade from HTTP to the Web Socket Protocol, after which messages received by the server call handle_message in the callback module, and messages can be sent on the Websocket using yaws_api:websocket_send/2.
The callback module should implement a function handle_message as follows:
handle_message({Type, Data}) -> HandlerResult
Type :: text|binary
Data :: binary()
HandlerResult :: {reply, {Type, Data}}
| {noreply}
| {close, Reason}When not replying to a message from a client, you can send messages using
yaws_api:websocket_send(Pid, {Type, Data})Enough theory for now. Sample echo server follows!
out(A) -> CallbackMod = basic_echo_callback, Opts = [{origin, "http://" ++ (A#arg.headers)#headers.host}], {websocket, CallbackMod, Opts}.
The above code can be executed Here.