- Notifications
You must be signed in to change notification settings - Fork604
A WebSocket Implementation for Node.JS (Draft -08 through the final RFC 6455)
License
theturtle32/WebSocket-Node
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
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.
You can read the full API documentation in the docs folder.
Current Version: 1.0.34 - Release 2021-04-14
- Updated browser shim to use the native
globalThis
property when available. Seethis MDN page for context. Resolves#415
All current browsers are fully* supported.
- Firefox 7-9 (Old) (Protocol Version 8)
- Firefox 10+ (Protocol Version 13)
- Chrome 14,15 (Old) (Protocol Version 8)
- Chrome 16+ (Protocol Version 13)
- Internet Explorer 10+ (Protocol Version 13)
- Safari 6+ (Protocol Version 13)
(Not all W3C WebSocket features are supported by browsers. More info in theFull API documentation)
There are some basic benchmarking sections in the Autobahn test suite. I've put up abenchmark page 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.
(These benchmarks are quite a bit outdated at this point, so take them with a grain of salt. Anyone up for running new benchmarks? I'll link to your report.)
The very completeAutobahn Test Suite is used by most WebSocket implementations to test spec compliance and interoperability.
In your project root:
$ npm install websocket
Then in your code:
varWebSocketServer=require('websocket').server;varWebSocketClient=require('websocket').client;varWebSocketFrame=require('websocket').frame;varWebSocketRouter=require('websocket').router;varW3CWebSocket=require('websocket').w3cwebsocket;
- Licensed under the Apache License, Version 2.0
- Protocol version "8" and "13" (Draft-08 through the final RFC) framing and handshake
- Can handle/aggregate received fragmented messages
- Can fragment outgoing messages
- Router to mount multiple applications to various path and protocol combinations
- TLS supported for outbound connections via WebSocketClient
- TLS supported for server connections (use https.createServer instead of http.createServer)
- Thanks topors for confirming this!
- Cookie setting and parsing
- Tunable settings
- Max Receivable Frame Size
- Max Aggregate ReceivedMessage Size
- Whether to fragment outgoing messages
- Fragmentation chunk size for outgoing messages
- Whether to automatically send ping frames for the purposes of keepalive
- Keep-alive ping interval
- Whether or not to automatically assemble received fragments (allows application to handle individual fragments directly)
- How long to wait after sending a close frame for acknowledgment before closing the socket.
- W3C WebSocket API for applications running on both Node and browsers (via the
W3CWebSocket
class).
- No API for user-provided protocol extensions.
Here's a short example showing a server that echos back anything sent to it, whether utf-8 or binary.
#!/usr/bin/env nodevarWebSocketServer=require('websocket').server;varhttp=require('http');varserver=http.createServer(function(request,response){console.log((newDate())+' Received request for '+request.url);response.writeHead(404);response.end();});server.listen(8080,function(){console.log((newDate())+' Server is listening on port 8080');});wsServer=newWebSocketServer({httpServer:server,// You should not use autoAcceptConnections for production// applications, as it defeats all standard cross-origin protection// facilities built into the protocol and the browser. You should// *always* verify the connection's origin and decide whether or not// to accept it.autoAcceptConnections:false});functionoriginIsAllowed(origin){// put logic here to detect whether the specified origin is allowed.returntrue;}wsServer.on('request',function(request){if(!originIsAllowed(request.origin)){// Make sure we only accept requests from an allowed originrequest.reject();console.log((newDate())+' Connection from origin '+request.origin+' rejected.');return;}varconnection=request.accept('echo-protocol',request.origin);console.log((newDate())+' Connection accepted.');connection.on('message',function(message){if(message.type==='utf8'){console.log('Received Message: '+message.utf8Data);connection.sendUTF(message.utf8Data);}elseif(message.type==='binary'){console.log('Received Binary Message of '+message.binaryData.length+' bytes');connection.sendBytes(message.binaryData);}});connection.on('close',function(reasonCode,description){console.log((newDate())+' Peer '+connection.remoteAddress+' disconnected.');});});
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.
This code demonstrates a client in Node.js, not in the browser
#!/usr/bin/env nodevarWebSocketClient=require('websocket').client;varclient=newWebSocketClient();client.on('connectFailed',function(error){console.log('Connect Error: '+error.toString());});client.on('connect',function(connection){console.log('WebSocket Client Connected');connection.on('error',function(error){console.log("Connection Error: "+error.toString());});connection.on('close',function(){console.log('echo-protocol Connection Closed');});connection.on('message',function(message){if(message.type==='utf8'){console.log("Received: '"+message.utf8Data+"'");}});functionsendNumber(){if(connection.connected){varnumber=Math.round(Math.random()*0xFFFFFF);connection.sendUTF(number.toString());setTimeout(sendNumber,1000);}}sendNumber();});client.connect('ws://localhost:8080/','echo-protocol');
Same example as above but using theW3C WebSocket API.
varW3CWebSocket=require('websocket').w3cwebsocket;varclient=newW3CWebSocket('ws://localhost:8080/','echo-protocol');client.onerror=function(){console.log('Connection Error');};client.onopen=function(){console.log('WebSocket Client Connected');functionsendNumber(){if(client.readyState===client.OPEN){varnumber=Math.round(Math.random()*0xFFFFFF);client.send(number.toString());setTimeout(sendNumber,1000);}}sendNumber();};client.onclose=function(){console.log('echo-protocol Client Closed');};client.onmessage=function(e){if(typeofe.data==='string'){console.log("Received: '"+e.data+"'");}};
For an example of using the request router, seelibwebsockets-test-server.js
in thetest
folder.
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
About
A WebSocket Implementation for Node.JS (Draft -08 through the final RFC 6455)
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.