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{https://nodejs.org/}{\texttt{ Node}} application. It does not provide any abstraction other than the standard \href{https://html.spec.whatwg.org/multipage/comms.html\#network}{\texttt{ Web\+Socket API}}.

It also provides an abstraction for handling \href{https://html.spec.whatwg.org/multipage/comms.html\#server-sent-events}{\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_sockjs_client_node_modules_faye_websocket_README_autotoc_md28088}{}\doxysection{Installation}\label{md_sfcode_node_modules_sockjs_client_node_modules_faye_websocket_README_autotoc_md28088}

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

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_sockjs_client_node_modules_faye_websocket_README_autotoc_md28089}{}\doxysection{Handling Web\+Socket connections in Node}\label{md_sfcode_node_modules_sockjs_client_node_modules_faye_websocket_README_autotoc_md28089}
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_sockjs_client_node_modules_faye_websocket_README_autotoc_md28090}{}\doxysection{Using the Web\+Socket client}\label{md_sfcode_node_modules_sockjs_client_node_modules_faye_websocket_README_autotoc_md28090}
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 an object that will be passed to \href{https://nodejs.org/api/tls.html\#tls_tls_connect_options_callback}{\texttt{ {\ttfamily tls.\+connect()}}}.\hypertarget{md_sfcode_node_modules_sockjs_client_node_modules_faye_websocket_README_autotoc_md28091}{}\doxysection{Subprotocol negotiation}\label{md_sfcode_node_modules_sockjs_client_node_modules_faye_websocket_README_autotoc_md28091}
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_sockjs_client_node_modules_faye_websocket_README_autotoc_md28092}{}\doxysection{Protocol extensions}\label{md_sfcode_node_modules_sockjs_client_node_modules_faye_websocket_README_autotoc_md28092}
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_sockjs_client_node_modules_faye_websocket_README_autotoc_md28093}{}\doxysection{Initialization options}\label{md_sfcode_node_modules_sockjs_client_node_modules_faye_websocket_README_autotoc_md28093}
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 net} -\/ an object containing settings for the origin server that will be passed to \href{https://nodejs.org/api/net.html\#net_socket_connect_options_connectlistener}{\texttt{ {\ttfamily net.\+connect()}}}
\item {\ttfamily tls} -\/ an object containing TLS settings for the origin server, this will be passed to \href{https://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_sockjs_client_node_modules_faye_websocket_README_autotoc_md28094}{}\doxysection{Web\+Socket API}\label{md_sfcode_node_modules_sockjs_client_node_modules_faye_websocket_README_autotoc_md28094}
Both server-\/ and client-\/side {\ttfamily Web\+Socket} objects support the following API.


\begin{DoxyItemize}
\item $\ast$$\ast$`on(\textquotesingle{}open', function(event) \{\})\`{}$\ast$$\ast$ fires when the socket connection is established. Event has no attributes.
\item $\ast$$\ast$`on(\textquotesingle{}message', function(event) \{\}){\ttfamily $\ast$$\ast$ fires when the socket receives a message. Event has one attribute, $\ast$$\ast$}data{\ttfamily $\ast$$\ast$, which is either a}String{\ttfamily (for text frames) or a}Buffer$<$tt$>$(for binary frames).
\item $\ast$$\ast$on(\textquotesingle{}error\textquotesingle{}, function(event) \{\})\`{}$\ast$$\ast$ 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 $\ast$$\ast$`on(\textquotesingle{}close', function(event) \{\}){\ttfamily $\ast$$\ast$ fires when either the client or the server closes the connection. Event has two optional attributes, $\ast$$\ast$}code{\ttfamily $\ast$$\ast$ and $\ast$$\ast$}reason\`{}$\ast$$\ast$, that expose the status code and message sent by the peer that closed the connection.
\item $\ast$$\ast${\ttfamily send(message)}$\ast$$\ast$ accepts either a {\ttfamily String} or a {\ttfamily Buffer} and sends a text or binary message over the connection to the other peer.
\item $\ast$$\ast${\ttfamily ping(message, function() \{\})}$\ast$$\ast$ sends a ping frame with an optional message and fires the callback when a matching pong is received.
\item $\ast$$\ast${\ttfamily close(code, reason)}$\ast$$\ast$ closes the connection, sending the given status code and reason text, both of which are optional.
\item $\ast$$\ast${\ttfamily version}$\ast$$\ast$ is a string containing the version of the {\ttfamily Web\+Socket} protocol the connection is using.
\item $\ast$$\ast${\ttfamily protocol}$\ast$$\ast$ is a string (which may be empty) identifying the subprotocol the socket is using.
\end{DoxyItemize}\hypertarget{md_sfcode_node_modules_sockjs_client_node_modules_faye_websocket_README_autotoc_md28095}{}\doxysection{Handling Event\+Source connections in Node}\label{md_sfcode_node_modules_sockjs_client_node_modules_faye_websocket_README_autotoc_md28095}
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 $\ast$$\ast${\ttfamily url}$\ast$$\ast$ is a string containing the URL the client used to create the Event\+Source.
\item $\ast$$\ast${\ttfamily last\+Event\+Id}$\ast$$\ast$ 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 $\ast$$\ast${\ttfamily headers}$\ast$$\ast$ is an object containing custom headers to be set on the Event\+Source response.
\item $\ast$$\ast${\ttfamily retry}$\ast$$\ast$ is a number that tells the client how long (in seconds) it should wait after a dropped connection before attempting to reconnect.
\item $\ast$$\ast${\ttfamily ping}$\ast$$\ast$ 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. 