
\begin{DoxyItemize}
\item Travis CI build\+: \href{http://travis-ci.org/faye/faye-websocket-node}{\texttt{ }}
\item Autobahn tests\+: \href{http://faye.jcoglan.com/autobahn/servers/}{\texttt{ server}}, \href{http://faye.jcoglan.com/autobahn/clients/}{\texttt{ client}}
\end{DoxyItemize}

This is a general-\/purpose Web\+Socket implementation extracted from the \href{http://faye.jcoglan.com}{\texttt{ Faye}} project. It provides classes for easily building Web\+Socket servers and clients in Node. It does not provide a server itself, but rather makes it easy to handle Web\+Socket connections within an existing \href{http://nodejs.org/}{\texttt{ Node}} application. It does not provide any abstraction other than the standard \href{http://dev.w3.org/html5/websockets/}{\texttt{ Web\+Socket API}}.

It also provides an abstraction for handling \href{http://dev.w3.org/html5/eventsource/}{\texttt{ Event\+Source}} connections, which are one-\/way connections that allow the server to push data to the client. They are based on streaming HTTP responses and can be easier to access via proxies than Web\+Sockets.\hypertarget{md_sfcode_node_modules_faye_websocket_README_autotoc_md10323}{}\doxysection{Installation}\label{md_sfcode_node_modules_faye_websocket_README_autotoc_md10323}

\begin{DoxyCode}{0}
\DoxyCodeLine{\$ npm install faye-\/websocket }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_faye_websocket_README_autotoc_md10324}{}\doxysection{Handling Web\+Socket connections in Node}\label{md_sfcode_node_modules_faye_websocket_README_autotoc_md10324}
You can handle Web\+Sockets on the server side by listening for HTTP Upgrade requests, and creating a new socket for the request. This socket object exposes the usual Web\+Socket methods for receiving and sending messages. For example this is how you\textquotesingle{}d implement an echo server\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{var WebSocket = require('faye-\/websocket'),}
\DoxyCodeLine{    http      = require('http');}
\DoxyCodeLine{}
\DoxyCodeLine{var server = http.createServer();}
\DoxyCodeLine{}
\DoxyCodeLine{server.on('upgrade', function(request, socket, body) \{}
\DoxyCodeLine{  if (WebSocket.isWebSocket(request)) \{}
\DoxyCodeLine{    var ws = new WebSocket(request, socket, body);}
\DoxyCodeLine{    }
\DoxyCodeLine{    ws.on('message', function(event) \{}
\DoxyCodeLine{      ws.send(event.data);}
\DoxyCodeLine{    \});}
\DoxyCodeLine{    }
\DoxyCodeLine{    ws.on('close', function(event) \{}
\DoxyCodeLine{      console.log('close', event.code, event.reason);}
\DoxyCodeLine{      ws = null;}
\DoxyCodeLine{    \});}
\DoxyCodeLine{  \}}
\DoxyCodeLine{\});}
\DoxyCodeLine{}
\DoxyCodeLine{server.listen(8000); }

\end{DoxyCode}


{\ttfamily Web\+Socket} objects are also duplex streams, so you could replace the `ws.\+on(\textquotesingle{}message', ...)\`{} line with\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{ws.pipe(ws); }

\end{DoxyCode}


Note that under certain circumstances (notably a draft-\/76 client connecting through an HTTP proxy), the Web\+Socket handshake will not be complete after you call {\ttfamily new Web\+Socket()} because the server will not have received the entire handshake from the client yet. In this case, calls to {\ttfamily ws.\+send()} will buffer the message in memory until the handshake is complete, at which point any buffered messages will be sent to the client.

If you need to detect when the Web\+Socket handshake is complete, you can use the {\ttfamily onopen} event.

If the connection\textquotesingle{}s protocol version supports it, you can call {\ttfamily ws.\+ping()} to send a ping message and wait for the client\textquotesingle{}s response. This method takes a message string, and an optional callback that fires when a matching pong message is received. It returns {\ttfamily true} if and only if a ping message was sent. If the client does not support ping/pong, this method sends no data and returns {\ttfamily false}.


\begin{DoxyCode}{0}
\DoxyCodeLine{ws.ping('Mic check, one, two', function() \{}
\DoxyCodeLine{  // fires when pong is received}
\DoxyCodeLine{\}); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_faye_websocket_README_autotoc_md10325}{}\doxysection{Using the Web\+Socket client}\label{md_sfcode_node_modules_faye_websocket_README_autotoc_md10325}
The client supports both the plain-\/text {\ttfamily ws} protocol and the encrypted {\ttfamily wss} protocol, and has exactly the same interface as a socket you would use in a web browser. On the wire it identifies itself as {\ttfamily hybi-\/13}.


\begin{DoxyCode}{0}
\DoxyCodeLine{var WebSocket = require('faye-\/websocket'),}
\DoxyCodeLine{    ws        = new WebSocket.Client('ws://www.example.com/');}
\DoxyCodeLine{}
\DoxyCodeLine{ws.on('open', function(event) \{}
\DoxyCodeLine{  console.log('open');}
\DoxyCodeLine{  ws.send('Hello, world!');}
\DoxyCodeLine{\});}
\DoxyCodeLine{}
\DoxyCodeLine{ws.on('message', function(event) \{}
\DoxyCodeLine{  console.log('message', event.data);}
\DoxyCodeLine{\});}
\DoxyCodeLine{}
\DoxyCodeLine{ws.on('close', function(event) \{}
\DoxyCodeLine{  console.log('close', event.code, event.reason);}
\DoxyCodeLine{  ws = null;}
\DoxyCodeLine{\}); }

\end{DoxyCode}


The Web\+Socket client also lets you inspect the status and headers of the handshake response via its {\ttfamily status\+Code} and {\ttfamily headers} properties.

To connect via a proxy, set the {\ttfamily proxy} option to the HTTP origin of the proxy, including any authorization information, custom headers and TLS config you require. Only the {\ttfamily origin} setting is required.


\begin{DoxyCode}{0}
\DoxyCodeLine{var ws = new WebSocket.Client('ws://www.example.com/', [], \{}
\DoxyCodeLine{  proxy: \{}
\DoxyCodeLine{    origin:  'http://username:password@proxy.example.com',}
\DoxyCodeLine{    headers: \{'User-\/Agent': 'node'\},}
\DoxyCodeLine{    tls:     \{cert: fs.readFileSync('client.crt')\}}
\DoxyCodeLine{  \}}
\DoxyCodeLine{\}); }

\end{DoxyCode}


The {\ttfamily tls} value is a Node \textquotesingle{}TLS options\textquotesingle{} object that will be passed to \href{http://nodejs.org/api/tls.html\#tls_tls_connect_options_callback}{\texttt{ {\ttfamily tls.\+connect()}}}.\hypertarget{md_sfcode_node_modules_faye_websocket_README_autotoc_md10326}{}\doxysection{Subprotocol negotiation}\label{md_sfcode_node_modules_faye_websocket_README_autotoc_md10326}
The Web\+Socket protocol allows peers to select and identify the application protocol to use over the connection. On the client side, you can set which protocols the client accepts by passing a list of protocol names when you construct the socket\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{var ws = new WebSocket.Client('ws://www.example.com/', ['irc', 'amqp']); }

\end{DoxyCode}


On the server side, you can likewise pass in the list of protocols the server supports after the other constructor arguments\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{var ws = new WebSocket(request, socket, body, ['irc', 'amqp']); }

\end{DoxyCode}


If the client and server agree on a protocol, both the client-\/ and server-\/side socket objects expose the selected protocol through the {\ttfamily ws.\+protocol} property.\hypertarget{md_sfcode_node_modules_faye_websocket_README_autotoc_md10327}{}\doxysection{Protocol extensions}\label{md_sfcode_node_modules_faye_websocket_README_autotoc_md10327}
faye-\/websocket is based on the \href{https://github.com/faye/websocket-extensions-node}{\texttt{ websocket-\/extensions}} framework that allows extensions to be negotiated via the {\ttfamily Sec-\/\+Web\+Socket-\/\+Extensions} header. To add extensions to a connection, pass an array of extensions to the {\ttfamily \+:extensions} option. For example, to add \href{https://github.com/faye/permessage-deflate-node}{\texttt{ permessage-\/deflate}}\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{var deflate = require('permessage-\/deflate');}
\DoxyCodeLine{}
\DoxyCodeLine{var ws = new WebSocket(request, socket, body, [], \{extensions: [deflate]\}); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_faye_websocket_README_autotoc_md10328}{}\doxysection{Initialization options}\label{md_sfcode_node_modules_faye_websocket_README_autotoc_md10328}
Both the server-\/ and client-\/side classes allow an options object to be passed in at initialization time, for example\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{var ws = new WebSocket(request, socket, body, protocols, options);}
\DoxyCodeLine{var ws = new WebSocket.Client(url, protocols, options); }

\end{DoxyCode}


{\ttfamily protocols} is an array of subprotocols as described above, or {\ttfamily null}. {\ttfamily options} is an optional object containing any of these fields\+:


\begin{DoxyItemize}
\item {\ttfamily extensions} -\/ an array of \href{https://github.com/faye/websocket-extensions-node}{\texttt{ websocket-\/extensions}} compatible extensions, as described above
\item {\ttfamily headers} -\/ an object containing key-\/value pairs representing HTTP headers to be sent during the handshake process
\item {\ttfamily max\+Length} -\/ the maximum allowed size of incoming message frames, in bytes. The default value is {\ttfamily 2$^\wedge$26 -\/ 1}, or 1 byte short of 64 MiB.
\item {\ttfamily ping} -\/ an integer that sets how often the Web\+Socket should send ping frames, measured in seconds
\end{DoxyItemize}

The client accepts some additional options\+:


\begin{DoxyItemize}
\item {\ttfamily proxy} -\/ settings for a proxy as described above
\item {\ttfamily tls} -\/ a Node \textquotesingle{}TLS options\textquotesingle{} object containing TLS settings for the origin server, this will be passed to \href{http://nodejs.org/api/tls.html\#tls_tls_connect_options_callback}{\texttt{ {\ttfamily tls.\+connect()}}}
\item {\ttfamily ca} -\/ (legacy) a shorthand for passing {\ttfamily \{tls\+: \{ca\+: value\}\}}
\end{DoxyItemize}\hypertarget{md_sfcode_node_modules_faye_websocket_README_autotoc_md10329}{}\doxysection{Web\+Socket API}\label{md_sfcode_node_modules_faye_websocket_README_autotoc_md10329}
Both server-\/ and client-\/side {\ttfamily Web\+Socket} objects support the following API.


\begin{DoxyItemize}
\item {\bfseries{`on(\textquotesingle{}open', function(event) \{\})\`{}}} fires when the socket connection is established. Event has no attributes.
\item {\bfseries{`on(\textquotesingle{}message', function(event) \{\}){\ttfamily $<$/b$>$ fires when the socket receives a message. Event has one attribute, $<$b$>$}data{\ttfamily $<$/b$>$, which is either a}String{\ttfamily  (for text frames) or a}Buffer$<$tt$>$(for binary frames).}}
\item {\bfseries{$<$b$>$on(\textquotesingle{}error\textquotesingle{}, function(event) \{\})\`{}}} fires when there is a protocol error due to bad data sent by the other peer. This event is purely informational, you do not need to implement error recover.
\item {\bfseries{`on(\textquotesingle{}close', function(event) \{\}){\ttfamily $<$/b$>$ fires when either the client or the server closes the connection. Event has two optional attributes, $<$b$>$}code{\ttfamily $<$/b$>$ and $<$b$>$}reason\`{}}}, that expose the status code and message sent by the peer that closed the connection.
\item {\bfseries{{\ttfamily send(message)}}} accepts either a {\ttfamily String} or a {\ttfamily Buffer} and sends a text or binary message over the connection to the other peer.
\item {\bfseries{{\ttfamily ping(message, function() \{\})}}} sends a ping frame with an optional message and fires the callback when a matching pong is received.
\item {\bfseries{{\ttfamily close(code, reason)}}} closes the connection, sending the given status code and reason text, both of which are optional.
\item {\bfseries{{\ttfamily version}}} is a string containing the version of the {\ttfamily Web\+Socket} protocol the connection is using.
\item {\bfseries{{\ttfamily protocol}}} is a string (which may be empty) identifying the subprotocol the socket is using.
\end{DoxyItemize}\hypertarget{md_sfcode_node_modules_faye_websocket_README_autotoc_md10330}{}\doxysection{Handling Event\+Source connections in Node}\label{md_sfcode_node_modules_faye_websocket_README_autotoc_md10330}
Event\+Source connections provide a very similar interface, although because they only allow the server to send data to the client, there is no {\ttfamily onmessage} API. Event\+Source allows the server to push text messages to the client, where each message has an optional event-\/type and ID.


\begin{DoxyCode}{0}
\DoxyCodeLine{var WebSocket   = require('faye-\/websocket'),}
\DoxyCodeLine{    EventSource = WebSocket.EventSource,}
\DoxyCodeLine{    http        = require('http');}
\DoxyCodeLine{}
\DoxyCodeLine{var server = http.createServer();}
\DoxyCodeLine{}
\DoxyCodeLine{server.on('request', function(request, response) \{}
\DoxyCodeLine{  if (EventSource.isEventSource(request)) \{}
\DoxyCodeLine{    var es = new EventSource(request, response);}
\DoxyCodeLine{    console.log('open', es.url, es.lastEventId);}
\DoxyCodeLine{    }
\DoxyCodeLine{    // Periodically send messages}
\DoxyCodeLine{    var loop = setInterval(function() \{ es.send('Hello') \}, 1000);}
\DoxyCodeLine{    }
\DoxyCodeLine{    es.on('close', function() \{}
\DoxyCodeLine{      clearInterval(loop);}
\DoxyCodeLine{      es = null;}
\DoxyCodeLine{    \});}
\DoxyCodeLine{  }
\DoxyCodeLine{  \} else \{}
\DoxyCodeLine{    // Normal HTTP request}
\DoxyCodeLine{    response.writeHead(200, \{'Content-\/Type': 'text/plain'\});}
\DoxyCodeLine{    response.end('Hello');}
\DoxyCodeLine{  \}}
\DoxyCodeLine{\});}
\DoxyCodeLine{}
\DoxyCodeLine{server.listen(8000); }

\end{DoxyCode}


The {\ttfamily send} method takes two optional parameters, {\ttfamily event} and {\ttfamily id}. The default event-\/type is `\textquotesingle{}message'{\ttfamily with no ID. For example, to send a}notification{\ttfamily  event with ID}99\`{}\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{es.send('Breaking News!', \{event: 'notification', id: '99'\}); }

\end{DoxyCode}


The {\ttfamily Event\+Source} object exposes the following properties\+:


\begin{DoxyItemize}
\item {\bfseries{{\ttfamily url}}} is a string containing the URL the client used to create the Event\+Source.
\item {\bfseries{{\ttfamily last\+Event\+Id}}} is a string containing the last event ID received by the client. You can use this when the client reconnects after a dropped connection to determine which messages need resending.
\end{DoxyItemize}

When you initialize an Event\+Source with {\ttfamily new Event\+Source()}, you can pass configuration options after the {\ttfamily response} parameter. Available options are\+:


\begin{DoxyItemize}
\item {\bfseries{{\ttfamily headers}}} is an object containing custom headers to be set on the Event\+Source response.
\item {\bfseries{{\ttfamily retry}}} is a number that tells the client how long (in seconds) it should wait after a dropped connection before attempting to reconnect.
\item {\bfseries{{\ttfamily ping}}} is a number that tells the server how often (in seconds) to send \textquotesingle{}ping\textquotesingle{} packets to the client to keep the connection open, to defeat timeouts set by proxies. The client will ignore these messages.
\end{DoxyItemize}

For example, this creates a connection that allows access from any origin, pings every 15 seconds and is retryable every 10 seconds if the connection is broken\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{var es = new EventSource(request, response, \{}
\DoxyCodeLine{  headers: \{'Access-\/Control-\/Allow-\/Origin': '*'\},}
\DoxyCodeLine{  ping:    15,}
\DoxyCodeLine{  retry:   10}
\DoxyCodeLine{\}); }

\end{DoxyCode}


You can send a ping message at any time by calling {\ttfamily es.\+ping()}. Unlike Web\+Socket, the client does not send a response to this; it is merely to send some data over the wire to keep the connection alive.\hypertarget{md_sfcode_node_modules_faye_websocket_README_autotoc_md10331}{}\doxysection{License}\label{md_sfcode_node_modules_faye_websocket_README_autotoc_md10331}
(The MIT License)

Copyright (c) 2010-\/2015 James Coglan

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \textquotesingle{}Software\textquotesingle{}), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions\+:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED \textquotesingle{}AS IS\textquotesingle{}, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 