A WebSocket Implementation for Node.JS (Draft -08 through the final RFC 6455)

Overview

WebSocket Client & Server Implementation for Node

npm version

NPM Downloads

Codeship Status for theturtle32/WebSocket-Node

Overview

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.

Documentation

You can read the full API documentation in the docs folder.

Changelog

Current Version: 1.0.34 - Release 2021-04-14

  • Updated browser shim to use the native globalThis property when available. See this MDN page for context. Resolves #415

View the full changelog

Browser Support

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)

Benchmarks

There are some basic benchmarking sections in the Autobahn test suite. I've put up a benchmark 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.)

Autobahn Tests

The very complete Autobahn Test Suite is used by most WebSocket implementations to test spec compliance and interoperability.

Installation

In your project root:

$ npm install websocket

Then in your code:

var WebSocketServer = require('websocket').server;
var WebSocketClient = require('websocket').client;
var WebSocketFrame  = require('websocket').frame;
var WebSocketRouter = require('websocket').router;
var W3CWebSocket = require('websocket').w3cwebsocket;

Current Features:

  • 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 to pors 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).

Known Issues/Missing Features:

  • No API for user-provided protocol extensions.

Usage Examples

Server Example

Here's a short example showing a server that echos back anything sent to it, whether utf-8 or binary.

#!/usr/bin/env node
var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(8080, function() {
    console.log((new Date()) + ' Server is listening on port 8080');
});

wsServer = new WebSocketServer({
    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
});

function originIsAllowed(origin) {
  // put logic here to detect whether the specified origin is allowed.
  return true;
}

wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
      // Make sure we only accept requests from an allowed origin
      request.reject();
      console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
      return;
    }
    
    var connection = request.accept('echo-protocol', request.origin);
    console.log((new Date()) + ' Connection accepted.');
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);
            connection.sendUTF(message.utf8Data);
        }
        else if (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((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});

Client Example

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 node
var WebSocketClient = require('websocket').client;

var client = new WebSocketClient();

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 + "'");
        }
    });
    
    function sendNumber() {
        if (connection.connected) {
            var number = Math.round(Math.random() * 0xFFFFFF);
            connection.sendUTF(number.toString());
            setTimeout(sendNumber, 1000);
        }
    }
    sendNumber();
});

client.connect('ws://localhost:8080/', 'echo-protocol');

Client Example using the W3C WebSocket API

Same example as above but using the W3C WebSocket API.

var W3CWebSocket = require('websocket').w3cwebsocket;

var client = new W3CWebSocket('ws://localhost:8080/', 'echo-protocol');

client.onerror = function() {
    console.log('Connection Error');
};

client.onopen = function() {
    console.log('WebSocket Client Connected');

    function sendNumber() {
        if (client.readyState === client.OPEN) {
            var number = 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 (typeof e.data === 'string') {
        console.log("Received: '" + e.data + "'");
    }
};

Request Router Example

For an example of using the request router, see libwebsockets-test-server.js in the test folder.

Resources

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

Comments
  • chrome 16 kills the example server

    chrome 16 kills the example server

    if i run in the chrome console:

    websocket = new WebSocket('ws://****.l:8081/echo-protocol'); WebSocket Unexpected response code: 500

    the server just crashes with this exception:

    Wed Jan 25 2012 22:12:42 GMT-0800 (PST) Server is listening on port 8080

    /home/dev/.node_libraries/.npm/websocket/1.0.4/package/lib/WebSocketRequest.js:240 throw new Error("Specified protocol was not requested by the clien ^ Error: Specified protocol was not requested by the client. at WebSocketRequest.accept (/home/dev/.node_libraries/.npm/websocket/1.0.4/package/lib/WebSocketRequest.js:240:19) at WebSocketServer. (/var/www/pimcore-current/website/lib/socket_server.js:36:30) at WebSocketServer.emit (events.js:81:20) at WebSocketServer.handleUpgrade (/home/dev/.node_libraries/.npm/websocket/1.0.4/package/lib/WebSocketServer.js:179:14) at Server. (native) at Server.emit (events.js:81:20) at Socket. (http.js:1035:14) at Socket._onReadable (net.js:683:27) at IOWatcher.onReadable as callback

    using this example code:

    
    var WebSocketServer = require('websocket').server;
    var http = require('http');
    
    var server = http.createServer(function(request, response) {
        console.log((new Date()) + ' Received request for ' + request.url);
        response.writeHead(404);
        response.end();
    });
    server.listen(8081, function() {
        console.log((new Date()) + ' Server is listening on port 8080');
    });
    
    wsServer = new WebSocketServer({
        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
    });
    
    function originIsAllowed(origin) {
      // put logic here to detect whether the specified origin is allowed.
      return true;
    }
    
    wsServer.on('request', function(request) {
        if (!originIsAllowed(request.origin)) {
          // Make sure we only accept requests from an allowed origin
          request.reject();
          console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
          return;
        }
    
        var connection = request.accept('echo-protocol', request.origin);
        console.log((new Date()) + ' Connection accepted.');
        connection.on('message', function(message) {
            if (message.type === 'utf8') {
                console.log('Received Message: ' + message.utf8Data);
                connection.sendUTF(message.utf8Data);
            }
            else if (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((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
        });
    });
    

    any ideas?

    opened by timglabisch 30
  • Refactoring to use ws napi modules

    Refactoring to use ws napi modules

    • removed native modules
    • change imports
    • add napi dependencies for native modules

    Should probably be merged into a n-api branch.

    theturtle32/WebSocket-Node#284

    opened by andreek 24
  • Improve tlsOptions documentation

    Improve tlsOptions documentation

    https://github.com/theturtle32/WebSocket-Node/blob/master/docs/WebSocketClient.md says:

    tlsOptions - object - Default: {} Options to pass to https.connect if connecting via TLS

    There is no https.connect() on Node's https module, but https.request/get() and tls.connect() (which I suppose it what the doc wanted to say).

    However, TLS options are supposed to be placed into the options object of https.request() which, in fact, accepts also the same options as in tls.connect().

    So, what is the purpose of tlsOptions? AFAIU any desired TLS option should be placed in the requestOptions of the WebSocketClient.connect() method, am I wrong?

    Documentation 
    opened by ibc 23
  • Undefined is not a function

    Undefined is not a function

    We are running 100+ nodes and noticed about 10% of them dying daily with "undefined is not a function" and limited stack trace:

    "undefined is not a function date=Fri Sep 13 2013 03:53:09 GMT+0000 (UTC), pid=889, uid=502, gid=502, cwd=/opt/our/node-server, execPath=/usr/bin/node, version=v0.10.16, argv=[/usr/bin/node, /opt/our/node-server/our-node.js], rss=474451968, heapTotal=115795712, heapUsed=74638544, loadavg=[0.0087890625, 0.00537109375, 0], uptime=751948.812361802, trace=[column=13, file=node.js, function=process._tickCallback, line=415, method=_tickCallback, native=false], stack=[TypeError: undefined is not a function,     at process._tickCallback (node.js:415:13)]"
    

    I have scanned the code to check where function to nextTick is not wrapped and only found two instances in websocket lib and in express ( middleware / limit.js ).

    I have then added additional check before calling next tick to check whether callback is undefined, so in WebsocketConnection.js it was:

        process.nextTick(this.outgoingFrameQueueHandler);
    +       if ( !this.outgoingFrameQueueHandler ) {
    +           throw new Error( "nextTick will crash node - WebsocketConnection.js" );
    +       }
    

    And few hours later I got the crash:

    "Thu, 19 Sep 2013 16: 16: 21 GMT - error: uncaughtException: nextTick will crash node - WebsocketConnection.js date = Thu Sep 19 2013 16: 16: 21 GMT + 0000(UTC),
    pid = 2213,
    uid = 502,
    gid = 502,
    cwd = /opt/our / node - server,
    execPath = /usr/bin / node,
    version = v0.10.16,
    argv = [/usr/bin / node, /opt/our / node - server / ournode.js],
    rss = 236617728,
    heapTotal = 103412480,
    heapUsed = 69955176,
    loadavg = [0, 0, 0],
    uptime = 1314941.257227379,
    trace = [column = 9, file = /opt/our / node - server / node_modules / websocket / lib / WebSocketConnection.js,
        function = WebSocketConnection.processOutgoingFrameQueue, line = 715, method = processOutgoingFrameQueue, native = false, column = 14, file = /opt/our / node - server / node_modules / websocket / lib / WebSocketConnection.js,
        function = WebSocketConnection.sendFrame, line = 674, method = sendFrame, native = false, column = 10, file = /opt/our / node - server / node_modules / websocket / lib / WebSocketConnection.js,
        function = WebSocketConnection.sendCloseFrame, line = 661, method = sendCloseFrame, native = false, column = 14, file = /opt/our / node - server / node_modules / websocket / lib / WebSocketConnection.js,
        function = WebSocketConnection.drop, line = 330, method = drop, native = false, column = 18, file = /opt/our / node - server / node_modules / websocket / lib / WebSocketConnection.js,
        function = WebSocketConnection.handleSocketData, line = 240, method = handleSocketData, native = false, column = 17, file = events.js,
        function = CleartextStream.EventEmitter.emit, line = 95, method = EventEmitter.emit, native = false, column = 14, file = _stream_readable.js,
        function = , line = 738, method = null, native = false, column = 17, file = events.js,
        function = CleartextStream.EventEmitter.emit, line = 92, method = EventEmitter.emit, native = false, column = 10, file = _stream_readable.js,
        function = emitDataEvents, line = 763, method = null, native = false, column = 5, file = _stream_readable.js,
        function = CleartextStream.Readable.on, line = 684, method = Readable.on, native = false
    ],
    stack = [Error: nextTick will crash node - WebsocketConnection.js, at WebSocketConnection.processOutgoingFrameQueue(/opt/our / node - server / node_modules / websocket / lib / WebSocketConnection.js: 715: 9), at WebSocketConnection.sendFrame(/opt/our / node - server / node_modules / websocket / lib / WebSocketConnection.js: 674: 14), at WebSocketConnection.sendCloseFrame(/opt/our / node - server / node_modules / websocket / lib / WebSocketConnection.js: 661: 10), at WebSocketConnection.drop(/opt/our / node - server / node_modules / websocket / lib / WebSocketConnection.js: 330: 14), at WebSocketConnection.handleSocketData(/opt/our / node - server / node_modules / websocket / lib / WebSocketConnection.js: 240: 18), at CleartextStream.EventEmitter.emit(events.js: 95: 17), at CleartextStream. < anonymous > (_stream_readable.js: 738: 14), at CleartextStream.EventEmitter.emit(events.js: 92: 17), at emitDataEvents(_stream_readable.js: 763: 10), at CleartextStream.Readable.on(_stream_readable.js: 684: 5)]"
    

    Followed by "undefined is not a function" and node dying.

    I looked a little bit closer and noticed this.outgoingFrameQueueHandler that processOutgoingFrameQueue passes to nextTick is effectively "recursion" as in constructor we have:

      this.outgoingFrameQueueHandler = this.processOutgoingFrameQueue.bind(this);
    

    On http://blog.nodejs.org/2013/03/11/node-v0-10-0-stable/ (faster process.NextTick) if I understand it right it says that this kind of recursion should be changed to use setImmediate instead on nextTick as of node v10.

    I'm yet to find the exact scenario to reproduce it every time and confirm setImmediate fix but thought I'll share my findings straight away.

    opened by sajkog 20
  • problem with wss

    problem with wss

    Hi everybody, first i just want to say i'm french, so excuse me if my english is bad.

    So, i want to build an architecture with wss, i implement my certificates and they work. But now, when i'm connect on the browser, my program create websocket and close it directly, i don't understand why, this is my code:

    file node

    var fs = require('fs');
    //var https = require('https');
    var WebSocketServer = require('websocket').server;
    var express = require('express');
    
    var serverTLS = express.createServer({
            key: fs.readFileSync(__dirname + '/notification_mail/notification.mail.com.key'),
            cert: fs.readFileSync(__dirname + '/notification_mail/notification.mail.com.crt')
    });
    
    serverTLS.configure(function(){
            serverTLS.set('views',__dirname);
            serverTLS.set('view engine','ejs');
    });
    
    serverTLS.get('/',function(req,res){
            res.render('index',{layout: false });
    });
    
    serverTLS.listen(443);
    
    var wss = new WebSocketServer({ httpServer: serverTLS, autoAcceptConnections: true });
    
    wss.on('connect', function(connection) {
            console.log((new Date()) + " Connection accepted.");
    
            connection.on('message', function(message) {
                    console.log("Received Message: " + message.utf8Data);
                    connection.sendUTF(message.utf8Data);
            });
    
            connection.on('close', function(connection) {
                    console.log((new Date()) + " Disconnected");
            });
    });
    
    console.log("Server launch");
    
    

    file html

     <body>
      <h1>Serveur 2</h1>
      <div id="tchat"></div>
      <script>
        //var url = "wss://" + document.URL.substr(7).split('/')[0];
        var url = "wss://notification.mail.com:443";
        var Text;
        var wsCtor = window['MozWebSocket'] ? MozWebSocket : WebSocket;
        this.socket = new wsCtor(url, 'connect');
    
        var stringRouteur = prompt('Enter list(s) (separated by coma)') || 'user';
        //routeur = stringRouteur.split(',');
        this.socket.send(JSON.stringify({ msg : 'routeur', data  : stringRouteur }));
        this.socket.onmessage = function(message){
            try{
                    var command = JSON.parse(message.data);
                    Text =  command.data;
                    html = '<div class="line"><b>'+message+'</div>';
                      document.getElementById('tchat').innerHTML += '<div class="line"><b>'+Text+'</b>';
    
            }
            catch(e){
                    alert("erreur");
            }
    
        }
        this.socket.onclose = function(){
            alert ("Connection lost");
        }
        </script>
    </body>
    
    

    if you have an idea about the problem :)

    opened by johnnyrubin 20
  • Close handshake: fixed status code and close reason

    Close handshake: fixed status code and close reason

    Currently, WebSocketConnection.close() uses fixed status code (1000) and close reason (Normal connection closure) during the close handshake.

    If I understand RFC6455 correctly, on the close handshake (7.1.2) the only requirement is that the status code used be taken from those defined by the standard. Mind you, I may be wrongly considering these status codes to be meaningful to the server application level rather than WebSocket server level.

    Anyway, my use case is server-server peering. In such cases, being able to convey close status and reason that hint to why peering was torn down (1001-Peer restarting, 1008-Peer policy violation...) would be nice.

    I would appreciate hearing more on this.

    feature-request 
    opened by braytak 19
  • Error MSB8007: The platform for project 'validation.vcxproj' is invalid. Platform='x64'

    Error MSB8007: The platform for project 'validation.vcxproj' is invalid. Platform='x64'

    Hi there,

    Npm seems to be complaining about not being able to validate the package for x64 architecture. I've been playing around with installing/uninstalling Visual Studio 2010 and the Windows 7 SDK. But I guess I only need Visual Studio 2010. Not sure what's going on. I'm running Windows 7 Home Premium 64-bit with Visual Studio 2010 installed.

    $ npm install websocket npm http GET https://registry.npmjs.org/websocket npm http 304 https://registry.npmjs.org/websocket npm WARN package.json [email protected] No README.md file found!

    [email protected] install c:\Users\nils\workspace\node-projects\valgomat\node_modules\websocket node-gyp rebuild

    c:\Users\nils\workspace\node-projects\valgomat\node_modules\websocket>node "c:\Program Files\nodejs
    node_modules\npm\bin\node-gyp-bin....\node_modules\node-gyp\bin\node-gyp.js" rebuild C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.Cpp.InvalidPlatform.Targets(23,7): erro r MSB8007: The Platform for project 'validation.vcxproj' is invalid. Platform='x64'. You may be se eing this message because you are trying to build a project without a solution file, and have speci fied a non-default Platform that doesn't exist for this project. [c:\Users\nils\workspace\node-proj ects\valgomat\node_modules\websocket\build\validation.vcxproj] gyp ERR! build error gyp ERR! stack Error: C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe failed with exit c ode: 1 gyp ERR! stack at ChildProcess.onExit (c:\Program Files\nodejs\node_modules\npm\node_modules\nod e-gyp\lib\build.js:215:23) gyp ERR! stack at ChildProcess.EventEmitter.emit (events.js:91:17) gyp ERR! stack at Process._handle.onexit (child_process.js:674:10) gyp ERR! System Windows_NT 6.1.7600 gyp ERR! command "node" "c:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin
    node-gyp.js" "rebuild" gyp ERR! cwd c:\Users\nils\workspace\node-projects\valgomat\node_modules\websocket gyp ERR! node -v v0.8.6 gyp ERR! node-gyp -v v0.6.3 gyp ERR! not ok npm ERR! [email protected] install: node-gyp rebuild npm ERR! cmd "/c" "node-gyp rebuild" failed with 1 npm ERR! npm ERR! Failed at the [email protected] install script. npm ERR! This is most likely a problem with the websocket package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! node-gyp rebuild npm ERR! You can get their info via: npm ERR! npm owner ls websocket npm ERR! There is likely additional logging output above.

    npm ERR! System Windows_NT 6.1.7600 npm ERR! command "c:\Program Files\nodejs\node.exe" "c:\Program Files\nodejs\node_modules\npm \bin\npm-cli.js" "install" "websocket" npm ERR! cwd c:\Users\nils\workspace\node-projects\valgomat npm ERR! node -v v0.8.6 npm ERR! npm -v 1.1.48 npm ERR! code ELIFECYCLE npm ERR! npm ERR! Additional logging details can be found in: npm ERR! c:\Users\nils\workspace\node-projects\valgomat\npm-debug.log npm ERR! not ok code 0

    opened by nilsnh 19
  • make validator optional

    make validator optional

    The native validator is built using node-waf, which is not available on Windows or OSX prebuilt nodejs installations. It is therefore not possible to install this package using NPM on these systems.

    Would it be possible to make the validator optional, or to skip its installation if there is no node-waf?

    opened by crobi 19
  • package.json is included in the build files

    package.json is included in the build files

    Hi

    I just noticed that your

    lib\version.js file is looking for a version from package.json

    module.exports = require('../package.json').version;

    What this is doing internally, it exports all packege.json file as js module and adds it to the minified/uglified build.

    So in my build, I got your whole package.json file with all dependencies and settings for no reason.

    I also noticed that error with my build. I get around this by using node.env to pass it in like this:

    version: process.env.VERSION

    I do not know will this work for you but you will find a solution that fits your need.

    Please modify this so your packege.json will not be added to any build that someone will make while using your library.

    Regards

    opened by PMustard 17
  • Under heavy load, client connecting to a WebSocket may miss the first packet

    Under heavy load, client connecting to a WebSocket may miss the first packet

    I am on Node.js v0.10.12 and working with WebSocketClient.

    In Node.js (_stream_readable.js:678, or search "Readable.prototype.on"). Whenever the first "data" event on a Socket (as readable stream) is bound to a handler, all buffered data will be flushed synchronously and immediately.

    In WebSocketConnection.js, around line 71: this.socket.on('error', this.handleSocketError.bind(this)); this.socket.on('data', this.handleSocketData.bind(this)); this.socket.on('end', this.handleSocketEnd.bind(this)); this.socket.on('close', this.handleSocketClose.bind(this)); this.socket.on('drain', this.handleSocketDrain.bind(this));

    After binding to "data" event of the underlying Socket, Node.js will emit the first packet to "handleSocketData". But at that point, no one is binding to that event yet. So the first packet is missing.

    In our case, we wrote a simple Node.js chatroom client and loaded the box. We found that the first packet is always missing.

    Since I am working just on the WebSocketClient, the easy fix for me is at WebSocketClient.js around line 340 in the "succeedHandshake" call. I modified it as follow:

    • Pause the socket before "new WebSocketConnection()", by calling "this.socket.pause();"
    • Resume the socket after emitted "connect" event on WebSocketClient, by calling "this.socket.resume();"

    This may not be a good fix and just a rough idea of what's going on. Please fix it for both client and server scenario.

    Thanks!

    opened by compulim 16
  • Using WebSocket Secure (wss://) in the browser

    Using WebSocket Secure (wss://) in the browser

    Hi!

    I'm having troubles connecting to a WebSocket server via WebSocket Secure connection (wss://) from the browser. Standard connections (ws://) work fine.

    ws://

    ws

    wss://

    wss

    Server

    var https = require ('https');
    var express = require('express');
    var WebSocketServerConstructor = require('websocket').server;
    
    var options = {
      key: ...,
      cert: ...,
      requestCert: true,
      passphrase: ...,
      ca: [
        ...
      ]
    };
    
    var Application = express();
    
    var Server = https.createServer(options, Application);
    
    var WebSocketServer = new WebSocketServerConstructor({
      httpServer: Server,
      autoAcceptConnections: true
    });
    
    WebSocketServer.on('connect', function(request) {
      console.log('Hello!');
    });
    
    Server.listen(443, '0.0.0.0');
    

    Browser

    var Socket = new WebSocket('wss://api.example.com/');
    

    Is there any way how to establish a secure connection from the browser?

    Thanks in advance!

    opened by Baggz 16
  • install of websocket and immediatly disapear

    install of websocket and immediatly disapear

    Hello. I use websocket module on multiple project without problem.

    Now, I try to reinstall an existing project on a new linux computer, and to add each nodejs module manualy.

    Now comes "websocket" module.

    As you see below, the last version is downloaded, but no trace of it, nor in NPM package.json, nor in node_modules folder, nor at run

    [email protected]:~/NexoManager# npm install -g websocket --save --unsafe-perm
    + [email protected]
    updated 1 package in 5.706s
    [email protected]:~/NexoManager# npm ls websocket
    [email protected] /root/NexoManager
    `-- (empty)
    
    [email protected]:~/NexoManager#  node index.js
    ...
    > var ws = require("websocket")
    Uncaught Error: Cannot find module 'websocket'
    Require stack:
    - <repl>
        at Function.Module._resolveFilename (internal/modules/cjs/loader.js:815:15)
        at Function.Module._load (internal/modules/cjs/loader.js:667:27)
        at Module.require (internal/modules/cjs/loader.js:887:19)
        at require (internal/modules/cjs/helpers.js:74:18) {
      code: 'MODULE_NOT_FOUND',
      requireStack: [ '<repl>' ]
    }
    
    

    Install with verbose option gives:

    
    [email protected]:~/NexoManager# npm install -g websocket --save --unsafe-perm --loglevel verbose
    npm info it worked if it ends with ok
    npm verb cli [
    npm verb cli   '/usr/local/lib/nodejs/node-v12.21.0-linux-arm64/bin/node',
    npm verb cli   '/usr/local/lib/nodejs/node-v12.21.0-linux-arm64/bin/npm',
    npm verb cli   'install',
    npm verb cli   '-g',
    npm verb cli   'websocket',
    npm verb cli   '--save',
    npm verb cli   '--unsafe-perm',
    npm verb cli   '--loglevel',
    npm verb cli   'verbose'
    npm verb cli ]
    npm info using [email protected]
    npm info using [email protected]
    npm verb npm-session 87675b24ee6b3ebc
    npm http fetch GET 304 https://registry.npmjs.org/websocket 1188ms (from cache)
    npm timing stage:loadCurrentTree Completed in 1823ms
    npm timing stage:loadIdealTree:cloneCurrentTree Completed in 14ms
    npm timing stage:loadIdealTree:loadShrinkwrap Completed in 80ms
    npm http fetch GET 304 https://registry.npmjs.org/bufferutil 533ms (from cache)
    npm http fetch GET 304 https://registry.npmjs.org/es5-ext 570ms (from cache)
    npm http fetch GET 304 https://registry.npmjs.org/debug 703ms (from cache)
    npm http fetch GET 304 https://registry.npmjs.org/utf-8-validate 719ms (from cache)
    npm http fetch GET 304 https://registry.npmjs.org/typedarray-to-buffer 739ms (from cache)
    npm http fetch GET 304 https://registry.npmjs.org/yaeti 1186ms (from cache)
    npm http fetch GET 304 https://registry.npmjs.org/node-gyp-build 226ms (from cache)
    npm http fetch GET 304 https://registry.npmjs.org/ms 206ms (from cache)
    npm http fetch GET 304 https://registry.npmjs.org/next-tick 307ms (from cache)
    npm http fetch GET 304 https://registry.npmjs.org/es6-iterator 335ms (from cache)
    npm http fetch GET 304 https://registry.npmjs.org/es6-symbol 354ms (from cache)
    npm http fetch GET 304 https://registry.npmjs.org/d 202ms (from cache)
    npm http fetch GET 304 https://registry.npmjs.org/type 222ms (from cache)
    npm http fetch GET 304 https://registry.npmjs.org/ext 185ms (from cache)
    npm http fetch GET 304 https://registry.npmjs.org/is-typedarray 197ms (from cache)
    npm timing stage:loadIdealTree:loadAllDepsIntoIdealTree Completed in 3154ms
    npm timing stage:loadIdealTree Completed in 3322ms
    npm timing stage:generateActionsToTake Completed in 49ms
    npm verb correctMkdir /root/.npm/_locks correctMkdir not in flight; initializing
    npm verb lock using /root/.npm/_locks/staging-e3e75e99a08fb154.lock for /usr/local/lib/nodejs/node-v12.21.0-linux-arm64/lib/node_modules/.staging
    npm timing action:extract Completed in 246ms
    npm info lifecycle [email protected]~preuninstall: [email protected]
    npm info lifecycle [email protected]~uninstall: [email protected]
    npm verb unbuild rmStuff [email protected] from /usr/local/lib/nodejs/node-v12.21.0-linux-arm64/lib/node_modules
    npm info lifecycle [email protected]~postuninstall: [email protected]
    npm timing action:unbuild Completed in 25ms
    npm timing action:remove Completed in 133ms
    npm timing action:finalize Completed in 62ms
    npm timing action:refresh-package-json Completed in 41ms
    npm info lifecycle [email protected]~preinstall: [email protected]
    npm timing action:preinstall Completed in 5ms
    npm info linkStuff [email protected]
    npm timing action:build Completed in 9ms
    npm info lifecycle [email protected]~install: [email protected]
    npm timing action:install Completed in 5ms
    npm info lifecycle [email protected]~postinstall: [email protected]
    npm timing action:postinstall Completed in 5ms
    npm verb unlock done using /root/.npm/_locks/staging-e3e75e99a08fb154.lock for /usr/local/lib/nodejs/node-v12.21.0-linux-arm64/lib/node_modules/.staging
    npm timing stage:executeActions Completed in 617ms
    npm timing stage:rollbackFailedOptional Completed in 2ms
    npm timing stage:runTopLevelLifecycles Completed in 5833ms
    + [email protected]
    updated 1 package in 5.851s
    npm verb exit [ 0, true ]
    npm timing npm Completed in 8015ms
    npm info ok
    [email protected]:~/NexoManager#
    
    

    What happends ?

    Best regards.

    opened by pedefe 0
  • How to connect to multiple WebSockets?

    How to connect to multiple WebSockets?

    Hello.

    I used the client code on your npm page as my starting point. I'm able to connect to the server and everything works great (I'm able to get all the messages that the server sends and process them).

    My issue is that when I receive one of the messages, I'm supposed to connect to a different socket that the message provides (it gives me the URI) and close the existing socket.

    I'm hoping someone can tell me or point me to some code that will help me understand how to connect to multiple WebSockets.

    Also, where can I find a list of all the 'on' methods (like connectFailed, connect, close, message, etc.)?

    Thanks for the help, much appreciated!

    opened by sawhitegt3 0
  • Ssl using cloudflare

    Ssl using cloudflare

    Im trying to connect to ws that proxyed using cloudflare, it wint allow me.. If im trying with direct ip it works, but the tbe domain it wont, I tryed using http server and with https server(using cloudflare cert) any help on that?

    opened by OlympicAngel 0
  • Process pending frames when handling socket end

    Process pending frames when handling socket end

    When the socket emits end event we might still have to process the frames from the bufferList. One of the frames could be CONNECTION_CLOSE and we don't want to miss that and think that the server has terminated connection incorrectly.

    opened by indutny-signal 0
  • Server Feat: connection2w3cwebsocket

    Server Feat: connection2w3cwebsocket

    Your websockets do some good stuff but, for consistencies sake and perhaps some browserify action, I wanted to use the W3CWebsocket interface with a server connection. I had forked your project a while ago but I suppose I wasn't able to figure out how to get it done. Well, I got it done.

    Notes

    • connection2w3cwebsocket is a very simple function
    • W3CWebSocket now inherits W3CWebSocketWrapper and much of the guts have been moved over there
    • Right now, W3CWebSocket listens to the close event to cleanup it's client.
      • this covers client failure, close while connecting and normal closing
      • If ever a consumer decided to remove all event listeners for this, the client will not get cleaned up.
      • This is also the case for some of the connection close events. Hopefully, nobody does something silly
    • I didn't know what to name W3CWebSocketWrapper
    • I added some tests, effectively just copied the W3CWebSocket tests.
      • the server based W3CWebSocket doesn't emit an open event.
      • I considered doing a Promise.resolve() then opening it but I'm not sure if its relevant
      • I'm definitely open to to implementing one if that is important it really should be easy
    opened by formula1 0
Owner
Brian McKelvey
Brian McKelvey
WebSocket emulation - Node.js server

SockJS-node SockJS for enterprise Available as part of the Tidelift Subscription. The maintainers of SockJS and thousands of other packages are workin

SockJS 2k Nov 15, 2022
Simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js

ws: a Node.js WebSocket library ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and server implementation. Passes the quit

WebSockets 19.1k Nov 23, 2022
Mini Projeto de um chat-app usando o protocolo WebSocket através da lib 'ws' do node.js

CHAT-APP-WEBSOCKET Mini Projeto de um chat-app usando o protocolo WebSocket através da lib 'ws' do node.js Obs o intuito deste projeto não é o fronten

Vinicius dos Santos Rodrigues 4 Jul 14, 2022
Standards-compliant WebSocket client and server

faye-websocket This is a general-purpose WebSocket implementation extracted from the Faye project. It provides classes for easily building WebSocket s

null 582 Nov 14, 2022
Lightweight WebSocket lib with socket.io-like event handling, requests, and channels

ws-wrapper Lightweight and isomorphic Web Socket lib with socket.io-like event handling, Promise-based requests, and channels. What? Much like Socket.

Blake Miner 69 Jul 16, 2022
The cutest little WebSocket wrapper! 🧦

Sockette The cutest little WebSocket wrapper! ?? Sockette is a tiny (367 bytes) wrapper around WebSocket that will automatically reconnect if the conn

Luke Edwards 2.4k Nov 17, 2022
A Develop Tool to Test WebSocket, Socket.IO, Stomp, Bayeux, HTTP, TCP, UDP, WebRTC, DNS API.

A Develop Tool to Test WebSocket, Socket.IO, Stomp, Bayeux, HTTP, TCP, UDP, WebRTC, DNS API.

York Yao 24 Sep 6, 2022
WebSocket cat

WebSocket cat

WebSockets 1.6k Nov 27, 2022
How to build a chat using Lambda + WebSocket + API Gateway? (nodejs)

Description Source code for the lambda function from the screencast How to build a chat using Lambda + WebSocket + API Gateway? (nodejs) The reactjs c

Alex 18 Nov 9, 2022
A tiny Nuxt.js module for WebSocket interactions

@deepsource/nuxt-websocket A tiny Nuxt.js module for WebSocket interactions. This module is only compatible with Nuxt v2 at the moment. Setup Add @dee

DeepSource 22 Oct 24, 2022
A websocket-based reverse shell for XSS attacks.

CrossSiteShell A javascript/nodejs "reverse shell" that makes it easier to interact with the victim's browser during XSS attacks. Usage Run the follow

Rafael 13 Oct 7, 2022
Um bot feito utilizando a API baileys em WebSocket para o Whatsapp Multi-Devices.

Informação ?? O BaileysBot foi feito utilzando a API Baileys Caso encontre algum BUG, faça um Novo Issue! Requisitos ?? NodeJS Git Instalação ?? Para

null 8 Oct 28, 2022
JSON-RPC 2.0 implementation over WebSockets for Node.js and JavaScript/TypeScript

WebSockets for Node.js and JavaScript/TypeScript with JSON RPC 2.0 support on top. About The rpc-websockets library enables developers to easily imple

Elpheria 477 Nov 24, 2022
μWebSockets for Node.js back-ends :metal:

Simple, secure[1] & standards compliant[2] web server for the most demanding[3] of applications. Read more... A note on NPM drama ⚡ Simple performance

uNetworking AB 5.6k Nov 22, 2022
ONG-Node JS

Server Base - Proyecto ONG Envinroment setup Create database Copy .env.example to .env and fill with database credentials.

Alkemy 2 Dec 30, 2021
Sse-example - SSE (server-sent events) example using Node.js

sse-example SSE (server-sent events) example using Node.js SSE is a easy way to commutate with the client side in a single direction. it has loss cost

Jack 2 Mar 11, 2022
Node.js library to receive live stream chat events like comments and gifts in realtime from TikTok LIVE.

TikTok-Live-Connector A Node.js library to receive live stream events such as comments and gifts in realtime from TikTok LIVE by connecting to TikTok'

David 366 Nov 25, 2022
Unix dgram, seqpacket, etc binding for Node.js.

node-unix-socket node-unix-socket allows you to use some nonblocking unix sockets that are currently not supported by Node.js native modules, includin

Bytedance Inc. 30 Nov 7, 2022
⚡️The Fullstack React Framework — built on Next.js

The Fullstack React Framework "Zero-API" Data Layer — Built on Next.js — Inspired by Ruby on Rails Read the Documentation “Zero-API” data layer lets y

⚡️Blitz 12.3k Nov 21, 2022
it is websocket-store for using easily websocket

Socket-Store It is Websocket Store How to use 1. Install # npm npm install socket-store # yarn yarn add socket-store 2. Create MessageHandler and

nerdchanii 4 Sep 13, 2022