1 WebSocket Client & Server Implementation for Node
2 =================================================
4 [![npm version](https://badge.fury.io/js/websocket.svg)](http://badge.fury.io/js/websocket)
6 [![NPM Downloads](https://img.shields.io/npm/dm/websocket.svg)](https://www.npmjs.com/package/websocket)
8 [![NPM](https://nodei.co/npm/websocket.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/websocket/)
10 [![NPM](https://nodei.co/npm-dl/websocket.png?height=3)](https://nodei.co/npm/websocket/)
12 [ ![Codeship Status for theturtle32/WebSocket-Node](https://codeship.com/projects/70458270-8ee7-0132-7756-0a0cf4fe8e66/status?branch=master)](https://codeship.com/projects/61106)
16 This is a (mostly) pure JavaScript implementation of the WebSocket protocol versions 8 and 13 for Node. There are some example client and server applications that implement various interoperability testing protocols in the "test/scripts" folder.
18 For a WebSocket client written in ActionScript 3, see my [AS3WebScocket](https://github.com/theturtle32/AS3WebSocket) project.
24 [You can read the full API documentation in the docs folder.](docs/index.md)
30 ***Current Version: 1.0.30*** — Released 2019-09-12
32 * Moved gulp back to devDependencies
34 [View the full changelog](CHANGELOG.md)
39 All current browsers are fully supported.
41 * Firefox 7-9 (Old) (Protocol Version 8)
42 * Firefox 10+ (Protocol Version 13)
43 * Chrome 14,15 (Old) (Protocol Version 8)
44 * Chrome 16+ (Protocol Version 13)
45 * Internet Explorer 10+ (Protocol Version 13)
46 * Safari 6+ (Protocol Version 13)
48 ***Safari older than 6.0 is not supported since it uses a very old draft of WebSockets***
50 ***If you need to simultaneously support legacy browser versions that had implemented draft-75/draft-76/draft-00, take a look here: https://gist.github.com/1428579***
54 There are some basic benchmarking sections in the Autobahn test suite. I've put up a [benchmark page](http://theturtle32.github.com/WebSocket-Node/benchmarks/) that shows the results from the Autobahn tests run against AutobahnServer 0.4.10, WebSocket-Node 1.0.2, WebSocket-Node 1.0.4, and ws 0.3.4.
58 The very complete [Autobahn Test Suite](http://autobahn.ws/testsuite/) is used by most WebSocket implementations to test spec compliance and interoperability.
60 - [View Server Test Results](http://theturtle32.github.com/WebSocket-Node/test-report/servers/)
65 A few users have reported difficulties building the native extensions without first manually installing node-gyp. If you have trouble building the native extensions, make sure you've got a C++ compiler, and have done `npm install -g node-gyp` first.
67 Native extensions are optional, however, and WebSocket-Node will work even if the extensions cannot be compiled.
71 $ npm install websocket
76 var WebSocketServer = require('websocket').server;
77 var WebSocketClient = require('websocket').client;
78 var WebSocketFrame = require('websocket').frame;
79 var WebSocketRouter = require('websocket').router;
80 var W3CWebSocket = require('websocket').w3cwebsocket;
83 Note for Windows Users
84 ----------------------
85 Because there is a small C++ component used for validating UTF-8 data, you will need to install a few other software packages in addition to Node to be able to build this module:
87 - [Microsoft Visual C++](http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-cpp-express)
88 - [Python 2.7](http://www.python.org/download/) (NOT Python 3.x)
93 - Licensed under the Apache License, Version 2.0
94 - Protocol version "8" and "13" (Draft-08 through the final RFC) framing and handshake
95 - Can handle/aggregate received fragmented messages
96 - Can fragment outgoing messages
97 - Router to mount multiple applications to various path and protocol combinations
98 - TLS supported for outbound connections via WebSocketClient
99 - TLS supported for server connections (use https.createServer instead of http.createServer)
100 - Thanks to [pors](https://github.com/pors) for confirming this!
101 - Cookie setting and parsing
103 - Max Receivable Frame Size
104 - Max Aggregate ReceivedMessage Size
105 - Whether to fragment outgoing messages
106 - Fragmentation chunk size for outgoing messages
107 - Whether to automatically send ping frames for the purposes of keepalive
108 - Keep-alive ping interval
109 - Whether or not to automatically assemble received fragments (allows application to handle individual fragments directly)
110 - How long to wait after sending a close frame for acknowledgment before closing the socket.
111 - [W3C WebSocket API](http://www.w3.org/TR/websockets/) for applications running on both Node and browsers (via the `W3CWebSocket` class).
114 Known Issues/Missing Features:
115 ------------------------------
116 - No API for user-provided protocol extensions.
125 Here's a short example showing a server that echos back anything sent to it, whether utf-8 or binary.
129 var WebSocketServer = require('websocket').server;
130 var http = require('http');
132 var server = http.createServer(function(request, response) {
133 console.log((new Date()) + ' Received request for ' + request.url);
134 response.writeHead(404);
137 server.listen(8080, function() {
138 console.log((new Date()) + ' Server is listening on port 8080');
141 wsServer = new WebSocketServer({
143 // You should not use autoAcceptConnections for production
144 // applications, as it defeats all standard cross-origin protection
145 // facilities built into the protocol and the browser. You should
146 // *always* verify the connection's origin and decide whether or not
148 autoAcceptConnections: false
151 function originIsAllowed(origin) {
152 // put logic here to detect whether the specified origin is allowed.
156 wsServer.on('request', function(request) {
157 if (!originIsAllowed(request.origin)) {
158 // Make sure we only accept requests from an allowed origin
160 console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
164 var connection = request.accept('echo-protocol', request.origin);
165 console.log((new Date()) + ' Connection accepted.');
166 connection.on('message', function(message) {
167 if (message.type === 'utf8') {
168 console.log('Received Message: ' + message.utf8Data);
169 connection.sendUTF(message.utf8Data);
171 else if (message.type === 'binary') {
172 console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
173 connection.sendBytes(message.binaryData);
176 connection.on('close', function(reasonCode, description) {
177 console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
185 This is a simple example client that will print out any utf-8 messages it receives on the console, and periodically sends a random number.
187 *This code demonstrates a client in Node.js, not in the browser*
191 var WebSocketClient = require('websocket').client;
193 var client = new WebSocketClient();
195 client.on('connectFailed', function(error) {
196 console.log('Connect Error: ' + error.toString());
199 client.on('connect', function(connection) {
200 console.log('WebSocket Client Connected');
201 connection.on('error', function(error) {
202 console.log("Connection Error: " + error.toString());
204 connection.on('close', function() {
205 console.log('echo-protocol Connection Closed');
207 connection.on('message', function(message) {
208 if (message.type === 'utf8') {
209 console.log("Received: '" + message.utf8Data + "'");
213 function sendNumber() {
214 if (connection.connected) {
215 var number = Math.round(Math.random() * 0xFFFFFF);
216 connection.sendUTF(number.toString());
217 setTimeout(sendNumber, 1000);
223 client.connect('ws://localhost:8080/', 'echo-protocol');
226 Client Example using the *W3C WebSocket API*
227 --------------------------------------------
229 Same example as above but using the [W3C WebSocket API](http://www.w3.org/TR/websockets/).
232 var W3CWebSocket = require('websocket').w3cwebsocket;
234 var client = new W3CWebSocket('ws://localhost:8080/', 'echo-protocol');
236 client.onerror = function() {
237 console.log('Connection Error');
240 client.onopen = function() {
241 console.log('WebSocket Client Connected');
243 function sendNumber() {
244 if (client.readyState === client.OPEN) {
245 var number = Math.round(Math.random() * 0xFFFFFF);
246 client.send(number.toString());
247 setTimeout(sendNumber, 1000);
253 client.onclose = function() {
254 console.log('echo-protocol Client Closed');
257 client.onmessage = function(e) {
258 if (typeof e.data === 'string') {
259 console.log("Received: '" + e.data + "'");
264 Request Router Example
265 ----------------------
267 For an example of using the request router, see `libwebsockets-test-server.js` in the `test` folder.
273 A presentation on the state of the WebSockets protocol that I gave on July 23, 2011 at the LA Hacker News meetup. [WebSockets: The Real-Time Web, Delivered](http://www.scribd.com/doc/60898569/WebSockets-The-Real-Time-Web-Delivered)