\href{https://www.npmjs.com/package/ws}{\texttt{ }} \href{https://travis-ci.com/websockets/ws}{\texttt{ }} \href{https://ci.appveyor.com/project/lpinca/ws}{\texttt{ }} \href{https://coveralls.io/github/websockets/ws}{\texttt{ }}

ws is a simple to use, blazing fast, and thoroughly tested Web\+Socket client and server implementation.

Passes the quite extensive Autobahn test suite\+: \href{http://websockets.github.io/ws/autobahn/servers/}{\texttt{ server}}, \href{http://websockets.github.io/ws/autobahn/clients/}{\texttt{ client}}.

{\bfseries{Note}}\+: This module does not work in the browser. The client in the docs is a reference to a back end with the role of a client in the Web\+Socket communication. Browser clients must use the native \href{https://developer.mozilla.org/en-US/docs/Web/API/WebSocket}{\texttt{ {\ttfamily Web\+Socket}}} object. To make the same code work seamlessly on Node.\+js and the browser, you can use one of the many wrappers available on npm, like \href{https://github.com/heineiuo/isomorphic-ws}{\texttt{ isomorphic-\/ws}}.\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8527}{}\doxysection{Table of Contents}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8527}

\begin{DoxyItemize}
\item \href{\#protocol-support}{\texttt{ Protocol support}}
\item \href{\#installing}{\texttt{ Installing}}
\begin{DoxyItemize}
\item \href{\#opt-in-for-performance-and-spec-compliance}{\texttt{ Opt-\/in for performance and spec compliance}}
\end{DoxyItemize}
\item \href{\#api-docs}{\texttt{ API docs}}
\item \href{\#websocket-compression}{\texttt{ Web\+Socket compression}}
\item \href{\#usage-examples}{\texttt{ Usage examples}}
\begin{DoxyItemize}
\item \href{\#sending-and-receiving-text-data}{\texttt{ Sending and receiving text data}}
\item \href{\#sending-binary-data}{\texttt{ Sending binary data}}
\item \href{\#simple-server}{\texttt{ Simple server}}
\item \href{\#external-https-server}{\texttt{ External HTTP/S server}}
\item \href{\#multiple-servers-sharing-a-single-https-server}{\texttt{ Multiple servers sharing a single HTTP/S server}}
\item \href{\#client-authentication}{\texttt{ Client authentication}}
\item \href{\#server-broadcast}{\texttt{ Server broadcast}}
\item \href{\#echowebsocketorg-demo}{\texttt{ echo.\+websocket.\+org demo}}
\item \href{\#use-the-nodejs-streams-api}{\texttt{ Use the Node.\+js streams API}}
\item \href{\#other-examples}{\texttt{ Other examples}}
\end{DoxyItemize}
\item \href{\#faq}{\texttt{ FAQ}}
\begin{DoxyItemize}
\item \href{\#how-to-get-the-ip-address-of-the-client}{\texttt{ How to get the IP address of the client?}}
\item \href{\#how-to-detect-and-close-broken-connections}{\texttt{ How to detect and close broken connections?}}
\item \href{\#how-to-connect-via-a-proxy}{\texttt{ How to connect via a proxy?}}
\end{DoxyItemize}
\item \href{\#changelog}{\texttt{ Changelog}}
\item \href{\#license}{\texttt{ License}}
\end{DoxyItemize}\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8528}{}\doxysection{Protocol support}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8528}

\begin{DoxyItemize}
\item {\bfseries{Hy\+Bi drafts 07-\/12}} (Use the option {\ttfamily protocol\+Version\+: 8})
\item {\bfseries{Hy\+Bi drafts 13-\/17}} (Current default, alternatively option {\ttfamily protocol\+Version\+: 13})
\end{DoxyItemize}\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8529}{}\doxysection{Installing}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8529}

\begin{DoxyCode}{0}
\DoxyCodeLine{npm install ws }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8530}{}\doxysubsection{Opt-\/in for performance and spec compliance}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8530}
There are 2 optional modules that can be installed along side with the ws module. These modules are binary addons which improve certain operations. Prebuilt binaries are available for the most popular platforms so you don\textquotesingle{}t necessarily need to have a C++ compiler installed on your machine.


\begin{DoxyItemize}
\item {\ttfamily npm install -\/-\/save-\/optional bufferutil}\+: Allows to efficiently perform operations such as masking and unmasking the data payload of the Web\+Socket frames.
\item {\ttfamily npm install -\/-\/save-\/optional utf-\/8-\/validate}\+: Allows to efficiently check if a message contains valid UTF-\/8 as required by the spec.
\end{DoxyItemize}\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8531}{}\doxysection{API docs}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8531}
See \`{}/doc/ws.md\`{} for Node.\+js-\/like documentation of ws classes and utility functions.\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8532}{}\doxysection{Web\+Socket compression}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8532}
ws supports the \href{https://tools.ietf.org/html/rfc7692}{\texttt{ permessage-\/deflate extension}} which enables the client and server to negotiate a compression algorithm and its parameters, and then selectively apply it to the data payloads of each Web\+Socket message.

The extension is disabled by default on the server and enabled by default on the client. It adds a significant overhead in terms of performance and memory consumption so we suggest to enable it only if it is really needed.

Note that Node.\+js has a variety of issues with high-\/performance compression, where increased concurrency, especially on Linux, can lead to \href{https://github.com/nodejs/node/issues/8871}{\texttt{ catastrophic memory fragmentation}} and slow performance. If you intend to use permessage-\/deflate in production, it is worthwhile to set up a test representative of your workload and ensure Node.\+js/zlib will handle it with acceptable performance and memory usage.

Tuning of permessage-\/deflate can be done via the options defined below. You can also use {\ttfamily zlib\+Deflate\+Options} and {\ttfamily zlib\+Inflate\+Options}, which is passed directly into the creation of \href{https://nodejs.org/api/zlib.html\#zlib_zlib_createdeflateraw_options}{\texttt{ raw deflate/inflate streams}}.

See \href{https://github.com/websockets/ws/blob/master/doc/ws.md\#new-websocketserveroptions-callback}{\texttt{ the docs}} for more options.


\begin{DoxyCode}{0}
\DoxyCodeLine{const WebSocket = require('ws');}
\DoxyCodeLine{}
\DoxyCodeLine{const wss = new WebSocket.Server(\{}
\DoxyCodeLine{  port: 8080,}
\DoxyCodeLine{  perMessageDeflate: \{}
\DoxyCodeLine{    zlibDeflateOptions: \{}
\DoxyCodeLine{      // See zlib defaults.}
\DoxyCodeLine{      chunkSize: 1024,}
\DoxyCodeLine{      memLevel: 7,}
\DoxyCodeLine{      level: 3}
\DoxyCodeLine{    \},}
\DoxyCodeLine{    zlibInflateOptions: \{}
\DoxyCodeLine{      chunkSize: 10 * 1024}
\DoxyCodeLine{    \},}
\DoxyCodeLine{    // Other options settable:}
\DoxyCodeLine{    clientNoContextTakeover: true, // Defaults to negotiated value.}
\DoxyCodeLine{    serverNoContextTakeover: true, // Defaults to negotiated value.}
\DoxyCodeLine{    serverMaxWindowBits: 10, // Defaults to negotiated value.}
\DoxyCodeLine{    // Below options specified as default values.}
\DoxyCodeLine{    concurrencyLimit: 10, // Limits zlib concurrency for perf.}
\DoxyCodeLine{    threshold: 1024 // Size (in bytes) below which messages}
\DoxyCodeLine{    // should not be compressed.}
\DoxyCodeLine{  \}}
\DoxyCodeLine{\}); }

\end{DoxyCode}


The client will only use the extension if it is supported and enabled on the server. To always disable the extension on the client set the {\ttfamily per\+Message\+Deflate} option to {\ttfamily false}.


\begin{DoxyCode}{0}
\DoxyCodeLine{const WebSocket = require('ws');}
\DoxyCodeLine{}
\DoxyCodeLine{const ws = new WebSocket('ws://www.host.com/path', \{}
\DoxyCodeLine{  perMessageDeflate: false}
\DoxyCodeLine{\}); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8533}{}\doxysection{Usage examples}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8533}
\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8534}{}\doxysubsection{Sending and receiving text data}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8534}

\begin{DoxyCode}{0}
\DoxyCodeLine{const WebSocket = require('ws');}
\DoxyCodeLine{}
\DoxyCodeLine{const ws = new WebSocket('ws://www.host.com/path');}
\DoxyCodeLine{}
\DoxyCodeLine{ws.on('open', function open() \{}
\DoxyCodeLine{  ws.send('something');}
\DoxyCodeLine{\});}
\DoxyCodeLine{}
\DoxyCodeLine{ws.on('message', function incoming(data) \{}
\DoxyCodeLine{  console.log(data);}
\DoxyCodeLine{\}); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8535}{}\doxysubsection{Sending binary data}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8535}

\begin{DoxyCode}{0}
\DoxyCodeLine{const WebSocket = require('ws');}
\DoxyCodeLine{}
\DoxyCodeLine{const ws = new WebSocket('ws://www.host.com/path');}
\DoxyCodeLine{}
\DoxyCodeLine{ws.on('open', function open() \{}
\DoxyCodeLine{  const array = new Float32Array(5);}
\DoxyCodeLine{}
\DoxyCodeLine{  for (var i = 0; i < array.length; ++i) \{}
\DoxyCodeLine{    array[i] = i / 2;}
\DoxyCodeLine{  \}}
\DoxyCodeLine{}
\DoxyCodeLine{  ws.send(array);}
\DoxyCodeLine{\}); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8536}{}\doxysubsection{Simple server}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8536}

\begin{DoxyCode}{0}
\DoxyCodeLine{const WebSocket = require('ws');}
\DoxyCodeLine{}
\DoxyCodeLine{const wss = new WebSocket.Server(\{ port: 8080 \});}
\DoxyCodeLine{}
\DoxyCodeLine{wss.on('connection', function connection(ws) \{}
\DoxyCodeLine{  ws.on('message', function incoming(message) \{}
\DoxyCodeLine{    console.log('received: \%s', message);}
\DoxyCodeLine{  \});}
\DoxyCodeLine{}
\DoxyCodeLine{  ws.send('something');}
\DoxyCodeLine{\}); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8537}{}\doxysubsection{External HTTP/\+S server}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8537}

\begin{DoxyCode}{0}
\DoxyCodeLine{const fs = require('fs');}
\DoxyCodeLine{const https = require('https');}
\DoxyCodeLine{const WebSocket = require('ws');}
\DoxyCodeLine{}
\DoxyCodeLine{const server = https.createServer(\{}
\DoxyCodeLine{  cert: fs.readFileSync('/path/to/cert.pem'),}
\DoxyCodeLine{  key: fs.readFileSync('/path/to/key.pem')}
\DoxyCodeLine{\});}
\DoxyCodeLine{const wss = new WebSocket.Server(\{ server \});}
\DoxyCodeLine{}
\DoxyCodeLine{wss.on('connection', function connection(ws) \{}
\DoxyCodeLine{  ws.on('message', function incoming(message) \{}
\DoxyCodeLine{    console.log('received: \%s', message);}
\DoxyCodeLine{  \});}
\DoxyCodeLine{}
\DoxyCodeLine{  ws.send('something');}
\DoxyCodeLine{\});}
\DoxyCodeLine{}
\DoxyCodeLine{server.listen(8080); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8538}{}\doxysubsection{Multiple servers sharing a single HTTP/\+S server}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8538}

\begin{DoxyCode}{0}
\DoxyCodeLine{const http = require('http');}
\DoxyCodeLine{const WebSocket = require('ws');}
\DoxyCodeLine{const url = require('url');}
\DoxyCodeLine{}
\DoxyCodeLine{const server = http.createServer();}
\DoxyCodeLine{const wss1 = new WebSocket.Server(\{ noServer: true \});}
\DoxyCodeLine{const wss2 = new WebSocket.Server(\{ noServer: true \});}
\DoxyCodeLine{}
\DoxyCodeLine{wss1.on('connection', function connection(ws) \{}
\DoxyCodeLine{  // ...}
\DoxyCodeLine{\});}
\DoxyCodeLine{}
\DoxyCodeLine{wss2.on('connection', function connection(ws) \{}
\DoxyCodeLine{  // ...}
\DoxyCodeLine{\});}
\DoxyCodeLine{}
\DoxyCodeLine{server.on('upgrade', function upgrade(request, socket, head) \{}
\DoxyCodeLine{  const pathname = url.parse(request.url).pathname;}
\DoxyCodeLine{}
\DoxyCodeLine{  if (pathname === '/foo') \{}
\DoxyCodeLine{    wss1.handleUpgrade(request, socket, head, function done(ws) \{}
\DoxyCodeLine{      wss1.emit('connection', ws, request);}
\DoxyCodeLine{    \});}
\DoxyCodeLine{  \} else if (pathname === '/bar') \{}
\DoxyCodeLine{    wss2.handleUpgrade(request, socket, head, function done(ws) \{}
\DoxyCodeLine{      wss2.emit('connection', ws, request);}
\DoxyCodeLine{    \});}
\DoxyCodeLine{  \} else \{}
\DoxyCodeLine{    socket.destroy();}
\DoxyCodeLine{  \}}
\DoxyCodeLine{\});}
\DoxyCodeLine{}
\DoxyCodeLine{server.listen(8080); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8539}{}\doxysubsection{Client authentication}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8539}

\begin{DoxyCode}{0}
\DoxyCodeLine{const http = require('http');}
\DoxyCodeLine{const WebSocket = require('ws');}
\DoxyCodeLine{}
\DoxyCodeLine{const server = http.createServer();}
\DoxyCodeLine{const wss = new WebSocket.Server(\{ noServer: true \});}
\DoxyCodeLine{}
\DoxyCodeLine{wss.on('connection', function connection(ws, request, client) \{}
\DoxyCodeLine{  ws.on('message', function message(msg) \{}
\DoxyCodeLine{    console.log(`Received message \$\{msg\} from user \$\{client\}`);}
\DoxyCodeLine{  \});}
\DoxyCodeLine{\});}
\DoxyCodeLine{}
\DoxyCodeLine{server.on('upgrade', function upgrade(request, socket, head) \{}
\DoxyCodeLine{  // This function is not defined on purpose. Implement it with your own logic.}
\DoxyCodeLine{  authenticate(request, (err, client) => \{}
\DoxyCodeLine{    if (err || !client) \{}
\DoxyCodeLine{      socket.write('HTTP/1.1 401 Unauthorized\(\backslash\)r\(\backslash\)n\(\backslash\)r\(\backslash\)n');}
\DoxyCodeLine{      socket.destroy();}
\DoxyCodeLine{      return;}
\DoxyCodeLine{    \}}
\DoxyCodeLine{}
\DoxyCodeLine{    wss.handleUpgrade(request, socket, head, function done(ws) \{}
\DoxyCodeLine{      wss.emit('connection', ws, request, client);}
\DoxyCodeLine{    \});}
\DoxyCodeLine{  \});}
\DoxyCodeLine{\});}
\DoxyCodeLine{}
\DoxyCodeLine{server.listen(8080); }

\end{DoxyCode}


Also see the provided \href{./examples/express-session-parse}{\texttt{ example}} using {\ttfamily express-\/session}.\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8540}{}\doxysubsection{Server broadcast}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8540}
A client Web\+Socket broadcasting to all connected Web\+Socket clients, including itself.


\begin{DoxyCode}{0}
\DoxyCodeLine{const WebSocket = require('ws');}
\DoxyCodeLine{}
\DoxyCodeLine{const wss = new WebSocket.Server(\{ port: 8080 \});}
\DoxyCodeLine{}
\DoxyCodeLine{wss.on('connection', function connection(ws) \{}
\DoxyCodeLine{  ws.on('message', function incoming(data) \{}
\DoxyCodeLine{    wss.clients.forEach(function each(client) \{}
\DoxyCodeLine{      if (client.readyState === WebSocket.OPEN) \{}
\DoxyCodeLine{        client.send(data);}
\DoxyCodeLine{      \}}
\DoxyCodeLine{    \});}
\DoxyCodeLine{  \});}
\DoxyCodeLine{\}); }

\end{DoxyCode}


A client Web\+Socket broadcasting to every other connected Web\+Socket clients, excluding itself.


\begin{DoxyCode}{0}
\DoxyCodeLine{const WebSocket = require('ws');}
\DoxyCodeLine{}
\DoxyCodeLine{const wss = new WebSocket.Server(\{ port: 8080 \});}
\DoxyCodeLine{}
\DoxyCodeLine{wss.on('connection', function connection(ws) \{}
\DoxyCodeLine{  ws.on('message', function incoming(data) \{}
\DoxyCodeLine{    wss.clients.forEach(function each(client) \{}
\DoxyCodeLine{      if (client !== ws \&\& client.readyState === WebSocket.OPEN) \{}
\DoxyCodeLine{        client.send(data);}
\DoxyCodeLine{      \}}
\DoxyCodeLine{    \});}
\DoxyCodeLine{  \});}
\DoxyCodeLine{\}); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8541}{}\doxysubsection{echo.\+websocket.\+org demo}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8541}

\begin{DoxyCode}{0}
\DoxyCodeLine{const WebSocket = require('ws');}
\DoxyCodeLine{}
\DoxyCodeLine{const ws = new WebSocket('wss://echo.websocket.org/', \{}
\DoxyCodeLine{  origin: 'https://websocket.org'}
\DoxyCodeLine{\});}
\DoxyCodeLine{}
\DoxyCodeLine{ws.on('open', function open() \{}
\DoxyCodeLine{  console.log('connected');}
\DoxyCodeLine{  ws.send(Date.now());}
\DoxyCodeLine{\});}
\DoxyCodeLine{}
\DoxyCodeLine{ws.on('close', function close() \{}
\DoxyCodeLine{  console.log('disconnected');}
\DoxyCodeLine{\});}
\DoxyCodeLine{}
\DoxyCodeLine{ws.on('message', function incoming(data) \{}
\DoxyCodeLine{  console.log(`Roundtrip time: \$\{Date.now() -\/ data\} ms`);}
\DoxyCodeLine{}
\DoxyCodeLine{  setTimeout(function timeout() \{}
\DoxyCodeLine{    ws.send(Date.now());}
\DoxyCodeLine{  \}, 500);}
\DoxyCodeLine{\}); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8542}{}\doxysubsection{Use the Node.\+js streams API}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8542}

\begin{DoxyCode}{0}
\DoxyCodeLine{const WebSocket = require('ws');}
\DoxyCodeLine{}
\DoxyCodeLine{const ws = new WebSocket('wss://echo.websocket.org/', \{}
\DoxyCodeLine{  origin: 'https://websocket.org'}
\DoxyCodeLine{\});}
\DoxyCodeLine{}
\DoxyCodeLine{const duplex = WebSocket.createWebSocketStream(ws, \{ encoding: 'utf8' \});}
\DoxyCodeLine{}
\DoxyCodeLine{duplex.pipe(process.stdout);}
\DoxyCodeLine{process.stdin.pipe(duplex); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8543}{}\doxysubsection{Other examples}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8543}
For a full example with a browser client communicating with a ws server, see the examples folder.

Otherwise, see the test cases.\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8544}{}\doxysection{FAQ}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8544}
\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8545}{}\doxysubsection{How to get the IP address of the client?}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8545}
The remote IP address can be obtained from the raw socket.


\begin{DoxyCode}{0}
\DoxyCodeLine{const WebSocket = require('ws');}
\DoxyCodeLine{}
\DoxyCodeLine{const wss = new WebSocket.Server(\{ port: 8080 \});}
\DoxyCodeLine{}
\DoxyCodeLine{wss.on('connection', function connection(ws, req) \{}
\DoxyCodeLine{  const ip = req.socket.remoteAddress;}
\DoxyCodeLine{\}); }

\end{DoxyCode}


When the server runs behind a proxy like NGINX, the de-\/facto standard is to use the {\ttfamily X-\/\+Forwarded-\/\+For} header.


\begin{DoxyCode}{0}
\DoxyCodeLine{wss.on('connection', function connection(ws, req) \{}
\DoxyCodeLine{  const ip = req.headers['x-\/forwarded-\/for'].split(/\(\backslash\)s*,\(\backslash\)s*/)[0];}
\DoxyCodeLine{\}); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8546}{}\doxysubsection{How to detect and close broken connections?}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8546}
Sometimes the link between the server and the client can be interrupted in a way that keeps both the server and the client unaware of the broken state of the connection (e.\+g. when pulling the cord).

In these cases ping messages can be used as a means to verify that the remote endpoint is still responsive.


\begin{DoxyCode}{0}
\DoxyCodeLine{const WebSocket = require('ws');}
\DoxyCodeLine{}
\DoxyCodeLine{function noop() \{\}}
\DoxyCodeLine{}
\DoxyCodeLine{function heartbeat() \{}
\DoxyCodeLine{  this.isAlive = true;}
\DoxyCodeLine{\}}
\DoxyCodeLine{}
\DoxyCodeLine{const wss = new WebSocket.Server(\{ port: 8080 \});}
\DoxyCodeLine{}
\DoxyCodeLine{wss.on('connection', function connection(ws) \{}
\DoxyCodeLine{  ws.isAlive = true;}
\DoxyCodeLine{  ws.on('pong', heartbeat);}
\DoxyCodeLine{\});}
\DoxyCodeLine{}
\DoxyCodeLine{const interval = setInterval(function ping() \{}
\DoxyCodeLine{  wss.clients.forEach(function each(ws) \{}
\DoxyCodeLine{    if (ws.isAlive === false) return ws.terminate();}
\DoxyCodeLine{}
\DoxyCodeLine{    ws.isAlive = false;}
\DoxyCodeLine{    ws.ping(noop);}
\DoxyCodeLine{  \});}
\DoxyCodeLine{\}, 30000);}
\DoxyCodeLine{}
\DoxyCodeLine{wss.on('close', function close() \{}
\DoxyCodeLine{  clearInterval(interval);}
\DoxyCodeLine{\}); }

\end{DoxyCode}


Pong messages are automatically sent in response to ping messages as required by the spec.

Just like the server example above your clients might as well lose connection without knowing it. You might want to add a ping listener on your clients to prevent that. A simple implementation would be\+:


\begin{DoxyCode}{0}
\DoxyCodeLine{const WebSocket = require('ws');}
\DoxyCodeLine{}
\DoxyCodeLine{function heartbeat() \{}
\DoxyCodeLine{  clearTimeout(this.pingTimeout);}
\DoxyCodeLine{}
\DoxyCodeLine{  // Use `WebSocket\#terminate()`, which immediately destroys the connection,}
\DoxyCodeLine{  // instead of `WebSocket\#close()`, which waits for the close timer.}
\DoxyCodeLine{  // Delay should be equal to the interval at which your server}
\DoxyCodeLine{  // sends out pings plus a conservative assumption of the latency.}
\DoxyCodeLine{  this.pingTimeout = setTimeout(() => \{}
\DoxyCodeLine{    this.terminate();}
\DoxyCodeLine{  \}, 30000 + 1000);}
\DoxyCodeLine{\}}
\DoxyCodeLine{}
\DoxyCodeLine{const client = new WebSocket('wss://echo.websocket.org/');}
\DoxyCodeLine{}
\DoxyCodeLine{client.on('open', heartbeat);}
\DoxyCodeLine{client.on('ping', heartbeat);}
\DoxyCodeLine{client.on('close', function clear() \{}
\DoxyCodeLine{  clearTimeout(this.pingTimeout);}
\DoxyCodeLine{\}); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8547}{}\doxysubsection{How to connect via a proxy?}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8547}
Use a custom {\ttfamily http.\+Agent} implementation like \href{https://github.com/TooTallNate/node-https-proxy-agent}{\texttt{ https-\/proxy-\/agent}} or \href{https://github.com/TooTallNate/node-socks-proxy-agent}{\texttt{ socks-\/proxy-\/agent}}.\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8548}{}\doxysection{Changelog}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8548}
We\textquotesingle{}re using the Git\+Hub \href{https://github.com/websockets/ws/releases}{\texttt{ releases}} for changelog entries.\hypertarget{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8549}{}\doxysection{License}\label{md_sfcode_node_modules_engine_io_node_modules_ws_README_autotoc_md8549}
\mbox{[}MIT\mbox{]}(LICENSE) 