Chapter 7. Streaming

Sometimes you want to stream data from a server to a client, for example, for an Internet radio station or a service like Pandora or Ustream. Yaws can do this quite well and with minimal effort on the part of the programmer.

The difference between streamed data and a standard HTTP connection is that a stream can remain open for a long period of time (oftentimes hours or days) and send data to the client for that entire time. However, unlike WebSockets (see Chapter 6) a stream is a one-way data connection and will normally be binary data like music or video as opposed to textual data in a WebSocket.

Simple Streaming

To set up streaming in Yaws, the out/1 function should return the tuple {streamcontent, MimeType, FirstChunk} as in Example 7-1.

Example 7-1. Setting up streaming (stream.yaws)

 out(A) ->
    io:format("~nStarting audio stream~n"),
    spawn(streaming, stream_data, [self()]),
    {streamcontent, "audio/mp3", <<>>}.

You must also spawn a new process to actually send the data to the client. This is done in Example 7-1 with the call to spawn/3. This will create a new process and pass the process ID of the creating process, as shown in Example 7-2. When creating that process, the out/1 function passes its own PID via the self/0 function to the function streaming:stream_data/1.

To actually send the data to the stream, call the function yaws_api:stream_chunk_deliver/2 with the Yaws creating PID and the data to be sent. When the stream is finished, call yaws_api:stream_chunk_end/1 ...

Get Building Web Applications with Erlang now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.