ws is a simple to use WebSocket implementation, up-to-date against RFC-6455,
and probably the fastest WebSocket library for node.js.
Passes the quite extensive Autobahn test suite. See http://websockets.github.com/ws for the full reports.
- HyBi drafts 07-12 (Use the option
protocolVersion: 8) - HyBi drafts 13-17 (Current default, alternatively option
protocolVersion: 13)
npm install --save ws
There are 2 optional modules that can be installed along side with the ws
module. These modules are binary addons which improve certain operations, but as
they are binary addons they require compilation which can fail if no c++
compiler is installed on the host system.
npm install --save bufferutil: Improves internal buffer operations which allows for faster processing of masked WebSocket frames and general buffer operations.npm install --save utf-8-validate: The specification requires validation of invalid UTF-8 chars, some of these validations could not be done in JavaScript hence the need for a binary addon. In most cases you will already be validating the input that you receive for security purposes leading to double validation. But if you want to be 100% spec-conforming and have fast validation of UTF-8 then this module is a must.
constWebSocket=require('ws');constws=newWebSocket('ws://www.host.com/path');ws.on('open',functionopen(){ws.send('something');});ws.on('message',function(data,flags){// flags.binary will be set if a binary data is received.// flags.masked will be set if the data was masked.});constWebSocket=require('ws');constws=newWebSocket('ws://www.host.com/path');ws.on('open',functionopen(){vararray=newFloat32Array(5);for(vari=0;i<array.length;++i){array[i]=i/2;}ws.send(array,{binary: true,mask: true});});Setting mask, as done for the send options above, will cause the data to be
masked according to the WebSocket protocol. The same option applies for text
data.
constWebSocketServer=require('ws').Server;constwss=newWebSocketServer({port: 8080});wss.on('connection',functionconnection(ws){ws.on('message',functionincoming(message){console.log('received: %s',message);});ws.send('something');});constserver=require('http').createServer();consturl=require('url');constWebSocketServer=require('ws').Server;constwss=newWebSocketServer({server: server});constexpress=require('express');constapp=express();constport=4080;app.use(function(req,res){res.send({msg: "hello"});});wss.on('connection',functionconnection(ws){varlocation=url.parse(ws.upgradeReq.url,true);// you might use location.query.access_token to authenticate or share sessions// or ws.upgradeReq.headers.cookie (see http://stackoverflow.com/a/16395220/151312)ws.on('message',functionincoming(message){console.log('received: %s',message);});ws.send('something');});server.on('request',app);server.listen(port,function(){console.log('Listening on '+server.address().port)});constWebSocketServer=require('ws').Server;constwss=newWebSocketServer({port: 8080});// Broadcast to all.wss.broadcast=functionbroadcast(data){wss.clients.forEach(functioneach(client){client.send(data);});};wss.on('connection',functionconnection(ws){ws.on('message',functionmessage(data){// Broadcast to everyone else.wss.clients.forEach(functioneach(client){if(client!==ws)client.send(data);});});});// If the WebSocket is closed before the following send is attemptedws.send('something');// Errors (both immediate and async write errors) can be detected in an optional// callback. The callback is also the only way of being notified that data has// actually been sent.ws.send('something',functionack(error){// if error is not defined, the send has been completed,// otherwise the error object will indicate what failed.});// Immediate errors can also be handled with try/catch-blocks, but **note** that// since sends are inherently asynchronous, socket write failures will *not* be// captured when this technique is used.try{ws.send('something');}catch(e){/* handle error */}constWebSocket=require('ws');constws=newWebSocket('ws://echo.websocket.org/',{protocolVersion: 8,origin: 'http://websocket.org'});ws.on('open',functionopen(){console.log('connected');ws.send(Date.now().toString(),{mask: true});});ws.on('close',functionclose(){console.log('disconnected');});ws.on('message',functionmessage(data,flags){console.log('Roundtrip time: '+(Date.now()-parseInt(data))+'ms',flags);setTimeout(functiontimeout(){ws.send(Date.now().toString(),{mask: true});},500);});For a full example with a browser client communicating with a ws server, see the examples folder.
Note that the usage together with Express 3.0 is quite different from Express 2.x. The difference is expressed in the two different serverstats-examples.
Otherwise, see the test cases.
See /doc/ws.md for Node.js-like docs for the ws classes.
We're using the GitHub releases for changelog entries.