O'Reilly logo

Building Web Applications with Erlang by Zachary Kessin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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)

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

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required