<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="Loïc Hoguin based on a design from (Soft10) Pol Cámara">
<title>Nine Nines: Websocket handlers</title>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700,400italic' rel='stylesheet' type='text/css'>
<link href="/css/99s.css?r=7" rel="stylesheet">
<link rel="shortcut icon" href="/img/ico/favicon.ico">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="/img/ico/apple-touch-icon-114.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="/img/ico/apple-touch-icon-72.png">
<link rel="apple-touch-icon-precomposed" href="/img/ico/apple-touch-icon-57.png">
</head>
<body class="">
<header id="page-head">
<div id="topbar" class="container">
<div class="row">
<div class="span2">
<h1 id="logo"><a href="/" title="99s">99s</a></h1>
</div>
<div class="span10">
<div id="side-header">
<nav>
<ul>
<li><a title="Hear my thoughts" href="/articles">Articles</a></li>
<li><a title="Watch my talks" href="/talks">Talks</a></li>
<li class="active"><a title="Read the docs" href="/docs">Documentation</a></li>
<li><a title="Request my services" href="/services">Consulting & Training</a></li>
</ul>
</nav>
<ul id="social">
<li>
<a href="https://github.com/ninenines" title="Check my Github repositories"><img src="/img/ico_github.png" data-hover="/img/ico_github_alt.png" alt="Github"></a>
</li>
<li>
<a title="Contact me" href="mailto:[email protected]"><img src="/img/ico_mail.png" data-hover="/img/ico_mail_alt.png"></a>
</li>
</ul>
</div>
</div>
</div>
</div>
</header>
<div id="contents" class="two_col">
<div class="container">
<div class="row">
<div id="docs" class="span9 maincol">
<h1 class="lined-header"><span>Websocket handlers</span></h1>
<p>Websocket handlers provide an interface for upgrading HTTP/1.1 connections to Websocket and sending or receiving frames on the Websocket connection.</p>
<p>As Websocket connections are established through the HTTP/1.1 upgrade mechanism, Websocket handlers need to be able to first receive the HTTP request for the upgrade, before switching to Websocket and taking over the connection. They can then receive or send Websocket frames, handle incoming Erlang messages or close the connection.</p>
<h2 id="_upgrade">Upgrade</h2>
<p>The <code>init/2</code> callback is called when the request is received. To establish a Websocket connection, you must switch to the <code>cowboy_websocket</code> module:</p>
<div class="listingblock"><div class="content"><!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><b><font color="#000000">init</font></b>(<font color="#009900">Req</font>, <font color="#009900">State</font>) <font color="#990000">-></font>
{<font color="#FF6600">cowboy_websocket</font>, <font color="#009900">Req</font>, <font color="#009900">State</font>}<font color="#990000">.</font></tt></pre>
</div></div>
<p>Cowboy will perform the Websocket handshake immediately. Note that the handshake will fail if the client did not request an upgrade to Websocket.</p>
<p>The Req object becomes unavailable after this function returns. Any information required for proper execution of the Websocket handler must be saved in the state.</p>
<h2 id="_subprotocol">Subprotocol</h2>
<p>The client may provide a list of Websocket subprotocols it supports in the sec-websocket-protocol header. The server <strong>must</strong> select one of them and send it back to the client or the handshake will fail.</p>
<p>For example, a client could understand both STOMP and MQTT over Websocket, and provide the header:</p>
<div class="listingblock"><div class="content"><pre>sec-websocket-protocol: v12.stomp, mqtt</pre></div></div>
<p>If the server only understands MQTT it can return:</p>
<div class="listingblock"><div class="content"><pre>sec-websocket-protocol: mqtt</pre></div></div>
<p>This selection must be done in <code>init/2</code>. An example usage could be:</p>
<div class="listingblock"><div class="content"><!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><b><font color="#000000">init</font></b>(<font color="#009900">Req0</font>, <font color="#009900">State</font>) <font color="#990000">-></font>
<b><font color="#0000FF">case</font></b> <b><font color="#000000">cowboy_req:parse_header</font></b>(<font color="#990000"><<</font><font color="#FF0000">"sec-websocket-protocol"</font><font color="#990000">>></font>, <font color="#009900">Req0</font>) <b><font color="#0000FF">of</font></b>
<font color="#000080">undefined</font> <font color="#990000">-></font>
{<font color="#FF6600">cowboy_websocket</font>, <font color="#009900">Req0</font>, <font color="#009900">State</font>};
<font color="#009900">Subprotocols</font> <font color="#990000">-></font>
<b><font color="#0000FF">case</font></b> <b><font color="#000000">lists:keymember</font></b>(<font color="#990000"><<</font><font color="#FF0000">"mqtt"</font><font color="#990000">>></font>, <font color="#993399">1</font>, <font color="#009900">Subprotocols</font>) <b><font color="#0000FF">of</font></b>
<font color="#000080">true</font> <font color="#990000">-></font>
<font color="#009900">Req</font> <font color="#990000">=</font> <b><font color="#000000">cowboy_req:set_resp_header</font></b>(<font color="#990000"><<</font><font color="#FF0000">"sec-websocket-protocol"</font><font color="#990000">>></font>,
<font color="#990000"><<</font><font color="#FF0000">"mqtt"</font><font color="#990000">>></font>, <font color="#009900">Req0</font>),
{<font color="#FF6600">cowboy_websocket</font>, <font color="#009900">Req</font>, <font color="#009900">State</font>};
<font color="#000080">false</font> <font color="#990000">-></font>
<font color="#009900">Req</font> <font color="#990000">=</font> <b><font color="#000000">cowboy_req:reply</font></b>(<font color="#993399">400</font>, <font color="#009900">Req0</font>),
{<font color="#FF6600">ok</font>, <font color="#009900">Req</font>, <font color="#009900">State</font>}
<b><font color="#0000FF">end</font></b>
<b><font color="#0000FF">end</font></b><font color="#990000">.</font></tt></pre>
</div></div>
<h2 id="_post_upgrade_initialization">Post-upgrade initialization</h2>
<p>Cowboy has separate processes for handling the connection and requests. Because Websocket takes over the connection, the Websocket protocol handling occurs in a different process than the request handling.</p>
<p>This is reflected in the different callbacks Websocket handlers have. The <code>init/2</code> callback is called from the temporary request process and the <code>websocket_</code> callbacks from the connection process.</p>
<p>This means that some initialization cannot be done from <code>init/2</code>. Anything that would require the current pid, or be tied to the current pid, will not work as intended. The optional <code>websocket_init/1</code> can be used instead:</p>
<div class="listingblock"><div class="content"><!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><b><font color="#000000">websocket_init</font></b>(<font color="#009900">State</font>) <font color="#990000">-></font>
<b><font color="#000000">erlang:start_timer</font></b>(<font color="#993399">1000</font>, <b><font color="#000080">self</font></b>(), <font color="#990000"><<</font><font color="#FF0000">"Hello!"</font><font color="#990000">>></font>),
{<font color="#FF6600">ok</font>, <font color="#009900">State</font>}<font color="#990000">.</font></tt></pre>
</div></div>
<p>All Websocket callbacks share the same return values. This means that we can send frames to the client right after the upgrade:</p>
<div class="listingblock"><div class="content"><!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><b><font color="#000000">websocket_init</font></b>(<font color="#009900">State</font>) <font color="#990000">-></font>
{[{<font color="#FF6600">text</font>, <font color="#990000"><<</font><font color="#FF0000">"Hello!"</font><font color="#990000">>></font>}], <font color="#009900">State</font>}<font color="#990000">.</font></tt></pre>
</div></div>
<h2 id="_receiving_frames">Receiving frames</h2>
<p>Cowboy will call <code>websocket_handle/2</code> whenever a text, binary, ping or pong frame arrives from the client.</p>
<p>The handler can handle or ignore the frames. It can also send frames back to the client or stop the connection.</p>
<p>The following snippet echoes back any text frame received and ignores all others:</p>
<div class="listingblock"><div class="content"><!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><b><font color="#000000">websocket_handle</font></b>(<font color="#009900">Frame</font> <font color="#990000">=</font> {<font color="#FF6600">text</font>, <font color="#990000">_</font>}, <font color="#009900">State</font>) <font color="#990000">-></font>
{[<font color="#009900">Frame</font>], <font color="#009900">State</font>};
<b><font color="#000000">websocket_handle</font></b>(<font color="#009900">_Frame</font>, <font color="#009900">State</font>) <font color="#990000">-></font>
{<font color="#FF6600">ok</font>, <font color="#009900">State</font>}<font color="#990000">.</font></tt></pre>
</div></div>
<p>Note that ping and pong frames require no action from the handler as Cowboy will automatically reply to ping frames. They are provided for informative purposes only.</p>
<h2 id="_receiving_erlang_messages">Receiving Erlang messages</h2>
<p>Cowboy will call <code>websocket_info/2</code> whenever an Erlang message arrives.</p>
<p>The handler can handle or ignore the messages. It can also send frames to the client or stop the connection.</p>
<p>The following snippet forwards log messages to the client and ignores all others:</p>
<div class="listingblock"><div class="content"><!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><b><font color="#000000">websocket_info</font></b>({<b><font color="#000080">log</font></b>, <font color="#009900">Text</font>}, <font color="#009900">State</font>) <font color="#990000">-></font>
{[{<font color="#FF6600">text</font>, <font color="#009900">Text</font>}], <font color="#009900">State</font>};
<b><font color="#000000">websocket_info</font></b>(<font color="#009900">_Info</font>, <font color="#009900">State</font>) <font color="#990000">-></font>
{<font color="#FF6600">ok</font>, <font color="#009900">State</font>}<font color="#990000">.</font></tt></pre>
</div></div>
<h2 id="_sending_frames">Sending frames</h2>
<!-- @todo This will be deprecated and eventually replaced with a-->
<!-- {Commands, State} interface that allows providing more-->
<!-- functionality easily.-->
<p>All <code>websocket_</code> callbacks share return values. They may send zero, one or many frames to the client.</p>
<p>To send nothing, just return an ok tuple:</p>
<div class="listingblock"><div class="content"><!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><b><font color="#000000">websocket_info</font></b>(<font color="#009900">_Info</font>, <font color="#009900">State</font>) <font color="#990000">-></font>
{<font color="#FF6600">ok</font>, <font color="#009900">State</font>}<font color="#990000">.</font></tt></pre>
</div></div>
<p>To send one frame, return the frame to be sent:</p>
<div class="listingblock"><div class="content"><!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><b><font color="#000000">websocket_info</font></b>(<font color="#009900">_Info</font>, <font color="#009900">State</font>) <font color="#990000">-></font>
{[{<font color="#FF6600">text</font>, <font color="#990000"><<</font><font color="#FF0000">"Hello!"</font><font color="#990000">>></font>}], <font color="#009900">State</font>}<font color="#990000">.</font></tt></pre>
</div></div>
<p>You can send frames of any type: text, binary, ping, pong or close frames.</p>
<p>You can send many frames at the same time:</p>
<div class="listingblock"><div class="content"><!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><b><font color="#000000">websocket_info</font></b>(<font color="#009900">_Info</font>, <font color="#009900">State</font>) <font color="#990000">-></font>
{[
{<font color="#FF6600">text</font>, <font color="#FF0000">"Hello"</font>},
{<font color="#FF6600">text</font>, <font color="#990000"><<</font><font color="#FF0000">"world!"</font><font color="#990000">>></font>},
{<b><font color="#000080">binary</font></b>, <font color="#990000"><<</font><font color="#993399">0</font><font color="#990000">:</font><font color="#993399">8000</font><font color="#990000">>></font>}
], <font color="#009900">State</font>}<font color="#990000">.</font></tt></pre>
</div></div>
<p>They are sent in the given order.</p>
<h2 id="_keeping_the_connection_alive">Keeping the connection alive</h2>
<p>Cowboy will automatically respond to ping frames sent by the client. They are still forwarded to the handler for informative purposes, but no further action is required.</p>
<p>Cowboy does not send ping frames itself. The handler can do it if required. A better solution in most cases is to let the client handle pings. Doing it from the handler would imply having an additional timer per connection and this can be a considerable cost for servers that need to handle large numbers of connections.</p>
<p>Cowboy can be configured to close idle connections automatically. It is highly recommended to configure a timeout here, to avoid having processes linger longer than needed.</p>
<p>The <code>init/2</code> callback can set the timeout to be used for the connection. For example, this would make Cowboy close connections idle for more than 30 seconds:</p>
<div class="listingblock"><div class="content"><!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><b><font color="#000000">init</font></b>(<font color="#009900">Req</font>, <font color="#009900">State</font>) <font color="#990000">-></font>
{<font color="#FF6600">cowboy_websocket</font>, <font color="#009900">Req</font>, <font color="#009900">State</font>, #{
<font color="#0000FF">idle_timeout</font> <font color="#990000">=></font> <font color="#993399">30000</font>}}<font color="#990000">.</font></tt></pre>
</div></div>
<p>This value cannot be changed once it is set. It defaults to <code>60000</code>.</p>
<h2 id="_limiting_frame_sizes">Limiting frame sizes</h2>
<p>Cowboy accepts frames of any size by default. You should limit the size depending on what your handler may handle. You can do this via the <code>init/2</code> callback:</p>
<div class="listingblock"><div class="content"><!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><b><font color="#000000">init</font></b>(<font color="#009900">Req</font>, <font color="#009900">State</font>) <font color="#990000">-></font>
{<font color="#FF6600">cowboy_websocket</font>, <font color="#009900">Req</font>, <font color="#009900">State</font>, #{
<font color="#0000FF">max_frame_size</font> <font color="#990000">=></font> <font color="#993399">8000000</font>}}<font color="#990000">.</font></tt></pre>
</div></div>
<p>The lack of limit is historical. A future version of Cowboy will have a more reasonable default.</p>
<h2 id="_saving_memory">Saving memory</h2>
<p>The Websocket connection process can be set to hibernate after the callback returns.</p>
<p>Simply add an <code>hibernate</code> field to the returned tuple:</p>
<div class="listingblock"><div class="content"><!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><b><font color="#000000">websocket_init</font></b>(<font color="#009900">State</font>) <font color="#990000">-></font>
{[], <font color="#009900">State</font>, <font color="#FF6600">hibernate</font>}<font color="#990000">.</font>
<b><font color="#000000">websocket_handle</font></b>(<font color="#009900">_Frame</font>, <font color="#009900">State</font>) <font color="#990000">-></font>
{[], <font color="#009900">State</font>, <font color="#FF6600">hibernate</font>}<font color="#990000">.</font>
<b><font color="#000000">websocket_info</font></b>(<font color="#009900">_Info</font>, <font color="#009900">State</font>) <font color="#990000">-></font>
{[{<font color="#FF6600">text</font>, <font color="#990000"><<</font><font color="#FF0000">"Hello!"</font><font color="#990000">>></font>}], <font color="#009900">State</font>, <font color="#FF6600">hibernate</font>}<font color="#990000">.</font></tt></pre>
</div></div>
<p>It is highly recommended to write your handlers with hibernate enabled, as this allows to greatly reduce the memory usage. Do note however that an increase in the CPU usage or latency can be observed instead, in particular for the more busy connections.</p>
<h2 id="_closing_the_connection">Closing the connection</h2>
<p>The connection can be closed at any time, either by telling Cowboy to stop it or by sending a close frame.</p>
<p>To tell Cowboy to close the connection, use a stop tuple:</p>
<div class="listingblock"><div class="content"><!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><b><font color="#000000">websocket_info</font></b>(<font color="#009900">_Info</font>, <font color="#009900">State</font>) <font color="#990000">-></font>
{<font color="#FF6600">stop</font>, <font color="#009900">State</font>}<font color="#990000">.</font></tt></pre>
</div></div>
<p>Sending a <code>close</code> frame will immediately initiate the closing of the Websocket connection. Note that when sending a list of frames that include a close frame, any frame found after the close frame will not be sent.</p>
<p>The following example sends a close frame with a reason message:</p>
<div class="listingblock"><div class="content"><!-- Generator: GNU source-highlight 3.1.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><b><font color="#000000">websocket_info</font></b>(<font color="#009900">_Info</font>, <font color="#009900">State</font>) <font color="#990000">-></font>
{[{<font color="#FF6600">close</font>, <font color="#993399">1000</font>, <font color="#990000"><<</font><font color="#FF0000">"some-reason"</font><font color="#990000">>></font>}], <font color="#009900">State</font>}<font color="#990000">.</font></tt></pre>
</div></div>
<nav style="margin:1em 0">
<a style="float:left" href="https://ninenines.eu/docs/en/cowboy/2.7/guide/ws_protocol/">
The Websocket protocol
</a>
<a style="float:right" href="https://ninenines.eu/docs/en/cowboy/2.7/guide/streams/">
Streams
</a>
</nav>
</div>
<div class="span3 sidecol">
<h3>
Cowboy
2.7
User Guide
</h3>
<ul>
<li><a href="/docs/en/cowboy/2.7/guide">User Guide</a></li>
<li><a href="/docs/en/cowboy/2.7/manual">Function Reference</a></li>
</ul>
<h4 id="docs-nav">Navigation</h4>
<h4>Version select</h4>
<ul>
<li><a href="/docs/en/cowboy/2.7/guide">2.7</a></li>
<li><a href="/docs/en/cowboy/2.6/guide">2.6</a></li>
<li><a href="/docs/en/cowboy/2.5/guide">2.5</a></li>
<li><a href="/docs/en/cowboy/2.4/guide">2.4</a></li>
<li><a href="/docs/en/cowboy/2.3/guide">2.3</a></li>
<li><a href="/docs/en/cowboy/2.2/guide">2.2</a></li>
</ul>
<h3 id="_like_my_work__donate">Like my work? Donate!</h3>
<p>Donate to Loïc Hoguin because his work on Cowboy, Ranch, Gun and Erlang.mk is fantastic:</p>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" style="display:inline">
<input type="hidden" name="cmd" value="_donations">
<input type="hidden" name="business" value="[email protected]">
<input type="hidden" name="lc" value="FR">
<input type="hidden" name="item_name" value="Loic Hoguin">
<input type="hidden" name="item_number" value="99s">
<input type="hidden" name="currency_code" value="EUR">
<input type="hidden" name="bn" value="PP-DonationsBF:btn_donate_LG.gif:NonHosted">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/fr_FR/i/scr/pixel.gif" width="1" height="1">
</form><p>Recurring payment options are also available via <a href="https://github.com/sponsors/essen">GitHub Sponsors</a>. These funds are used to cover the recurring expenses like food, dedicated servers or domain names.</p>
</div>
</div>
</div>
</div>
<footer>
<div class="container">
<div class="row">
<div class="span6">
<p id="scroll-top"><a href="#">↑ Scroll to top</a></p>
<nav>
<ul>
<li><a href="mailto:[email protected]" title="Contact us">Contact us</a></li><li><a href="https://github.com/ninenines/ninenines.github.io" title="Github repository">Contribute to this site</a></li>
</ul>
</nav>
</div>
<div class="span6 credits">
<p><img src="/img/footer_logo.png"></p>
<p>Copyright © Loïc Hoguin 2012-2018</p>
</div>
</div>
</div>
</footer>
<script src="/js/custom.js"></script>
</body>
</html>