Standards-compliant WebSocket client and server

Overview

faye-websocket

This is a general-purpose WebSocket implementation extracted from the Faye project. It provides classes for easily building WebSocket servers and clients in Node. It does not provide a server itself, but rather makes it easy to handle WebSocket connections within an existing Node application. It does not provide any abstraction other than the standard WebSocket API.

It also provides an abstraction for handling EventSource connections, which are one-way connections that allow the server to push data to the client. They are based on streaming HTTP responses and can be easier to access via proxies than WebSockets.

Installation

$ npm install faye-websocket

Handling WebSocket connections in Node

You can handle WebSockets on the server side by listening for HTTP Upgrade requests, and creating a new socket for the request. This socket object exposes the usual WebSocket methods for receiving and sending messages. For example this is how you'd implement an echo server:

var WebSocket = require('faye-websocket'),
    http      = require('http');

var server = http.createServer();

server.on('upgrade', function(request, socket, body) {
  if (WebSocket.isWebSocket(request)) {
    var ws = new WebSocket(request, socket, body);

    ws.on('message', function(event) {
      ws.send(event.data);
    });

    ws.on('close', function(event) {
      console.log('close', event.code, event.reason);
      ws = null;
    });
  }
});

server.listen(8000);

WebSocket objects are also duplex streams, so you could replace the ws.on('message', ...) line with:

    ws.pipe(ws);

Note that under certain circumstances (notably a draft-76 client connecting through an HTTP proxy), the WebSocket handshake will not be complete after you call new WebSocket() because the server will not have received the entire handshake from the client yet. In this case, calls to ws.send() will buffer the message in memory until the handshake is complete, at which point any buffered messages will be sent to the client.

If you need to detect when the WebSocket handshake is complete, you can use the onopen event.

If the connection's protocol version supports it, you can call ws.ping() to send a ping message and wait for the client's response. This method takes a message string, and an optional callback that fires when a matching pong message is received. It returns true if and only if a ping message was sent. If the client does not support ping/pong, this method sends no data and returns false.

ws.ping('Mic check, one, two', function() {
  // fires when pong is received
});

Using the WebSocket client

The client supports both the plain-text ws protocol and the encrypted wss protocol, and has exactly the same interface as a socket you would use in a web browser. On the wire it identifies itself as hybi-13.

var WebSocket = require('faye-websocket'),
    ws        = new WebSocket.Client('ws://www.example.com/');

ws.on('open', function(event) {
  console.log('open');
  ws.send('Hello, world!');
});

ws.on('message', function(event) {
  console.log('message', event.data);
});

ws.on('close', function(event) {
  console.log('close', event.code, event.reason);
  ws = null;
});

The WebSocket client also lets you inspect the status and headers of the handshake response via its statusCode and headers properties.

To connect via a proxy, set the proxy option to the HTTP origin of the proxy, including any authorization information, custom headers and TLS config you require. Only the origin setting is required.

var ws = new WebSocket.Client('ws://www.example.com/', [], {
  proxy: {
    origin:  'http://username:[email protected]',
    headers: { 'User-Agent': 'node' },
    tls:     { cert: fs.readFileSync('client.crt') }
  }
});

The tls value is an object that will be passed to tls.connect().

Subprotocol negotiation

The WebSocket protocol allows peers to select and identify the application protocol to use over the connection. On the client side, you can set which protocols the client accepts by passing a list of protocol names when you construct the socket:

var ws = new WebSocket.Client('ws://www.example.com/', ['irc', 'amqp']);

On the server side, you can likewise pass in the list of protocols the server supports after the other constructor arguments:

var ws = new WebSocket(request, socket, body, ['irc', 'amqp']);

If the client and server agree on a protocol, both the client- and server-side socket objects expose the selected protocol through the ws.protocol property.

Protocol extensions

faye-websocket is based on the websocket-extensions framework that allows extensions to be negotiated via the Sec-WebSocket-Extensions header. To add extensions to a connection, pass an array of extensions to the :extensions option. For example, to add permessage-deflate:

var deflate = require('permessage-deflate');

var ws = new WebSocket(request, socket, body, [], { extensions: [deflate] });

Initialization options

Both the server- and client-side classes allow an options object to be passed in at initialization time, for example:

var ws = new WebSocket(request, socket, body, protocols, options);
var ws = new WebSocket.Client(url, protocols, options);

protocols is an array of subprotocols as described above, or null. options is an optional object containing any of these fields:

  • extensions - an array of websocket-extensions compatible extensions, as described above
  • headers - an object containing key-value pairs representing HTTP headers to be sent during the handshake process
  • maxLength - the maximum allowed size of incoming message frames, in bytes. The default value is 2^26 - 1, or 1 byte short of 64 MiB.
  • ping - an integer that sets how often the WebSocket should send ping frames, measured in seconds

The client accepts some additional options:

  • proxy - settings for a proxy as described above
  • net - an object containing settings for the origin server that will be passed to net.connect()
  • tls - an object containing TLS settings for the origin server, this will be passed to tls.connect()
  • ca - (legacy) a shorthand for passing { tls: { ca: value } }

WebSocket API

Both server- and client-side WebSocket objects support the following API.

  • on('open', function(event) {}) fires when the socket connection is established. Event has no attributes.
  • on('message', function(event) {}) fires when the socket receives a message. Event has one attribute, data, which is either a String (for text frames) or a Buffer (for binary frames).
  • on('error', function(event) {}) fires when there is a protocol error due to bad data sent by the other peer. This event is purely informational, you do not need to implement error recover.
  • on('close', function(event) {}) fires when either the client or the server closes the connection. Event has two optional attributes, code and reason, that expose the status code and message sent by the peer that closed the connection.
  • send(message) accepts either a String or a Buffer and sends a text or binary message over the connection to the other peer.
  • ping(message, function() {}) sends a ping frame with an optional message and fires the callback when a matching pong is received.
  • close(code, reason) closes the connection, sending the given status code and reason text, both of which are optional.
  • version is a string containing the version of the WebSocket protocol the connection is using.
  • protocol is a string (which may be empty) identifying the subprotocol the socket is using.

Handling EventSource connections in Node

EventSource connections provide a very similar interface, although because they only allow the server to send data to the client, there is no onmessage API. EventSource allows the server to push text messages to the client, where each message has an optional event-type and ID.

var WebSocket   = require('faye-websocket'),
    EventSource = WebSocket.EventSource,
    http        = require('http');

var server = http.createServer();

server.on('request', function(request, response) {
  if (EventSource.isEventSource(request)) {
    var es = new EventSource(request, response);
    console.log('open', es.url, es.lastEventId);

    // Periodically send messages
    var loop = setInterval(function() { es.send('Hello') }, 1000);

    es.on('close', function() {
      clearInterval(loop);
      es = null;
    });

  } else {
    // Normal HTTP request
    response.writeHead(200, { 'Content-Type': 'text/plain' });
    response.end('Hello');
  }
});

server.listen(8000);

The send method takes two optional parameters, event and id. The default event-type is 'message' with no ID. For example, to send a notification event with ID 99:

es.send('Breaking News!', { event: 'notification', id: '99' });

The EventSource object exposes the following properties:

  • url is a string containing the URL the client used to create the EventSource.
  • lastEventId is a string containing the last event ID received by the client. You can use this when the client reconnects after a dropped connection to determine which messages need resending.

When you initialize an EventSource with new EventSource(), you can pass configuration options after the response parameter. Available options are:

  • headers is an object containing custom headers to be set on the EventSource response.
  • retry is a number that tells the client how long (in seconds) it should wait after a dropped connection before attempting to reconnect.
  • ping is a number that tells the server how often (in seconds) to send 'ping' packets to the client to keep the connection open, to defeat timeouts set by proxies. The client will ignore these messages.

For example, this creates a connection that allows access from any origin, pings every 15 seconds and is retryable every 10 seconds if the connection is broken:

var es = new EventSource(request, response, {
  headers: { 'Access-Control-Allow-Origin': '*' },
  ping:    15,
  retry:   10
});

You can send a ping message at any time by calling es.ping(). Unlike WebSocket, the client does not send a response to this; it is merely to send some data over the wire to keep the connection alive.

Comments
  • Echo server runs out of RAM

    Echo server runs out of RAM

    The echo server example under any significant load exceeds available RAM very quickly.

    This appears to be because the example writes the received websocket frame directly back out without doing any flow control.

    The normal way to implement this in a scalable way using node is to use util.pump or stream.pipe, however the Fay WebSocket object does not appear to be usable in this way.

    Shouldn't the Websocket implement read and write streams as is normal with most node.js objects which read and write data?

    http://nodejs.org/api/stream.html

    opened by purplefox 33
  • Connections lost in API.CLOSING state causing EMFILE error

    Connections lost in API.CLOSING state causing EMFILE error

    Faye-websocket-node seems to be leaking socket descriptors when closing 'hixie' websockets.

    The culprint seems to be this hixie:close() function: https://github.com/faye/faye-websocket-node/blob/master/lib/faye/websocket/hybi_parser.js#L255-L260

    Which, as opposed to draft-76:close() function: https://github.com/faye/faye-websocket-node/blob/master/lib/faye/websocket/draft76_parser.js#L91-L96

    Doesn't seem to call callback immediately. This may result in callback not being called at all, and leaking a descriptor as a result.

    The side effect of that is the strange lsof message can't identify protocol, described here: https://idea.popcount.org/2012-12-09-lsof-cant-identify-protocol/

    More discussion: https://github.com/sockjs/sockjs-node/issues/99#issuecomment-11084738

    opened by majek 12
  • Compression support with

    Compression support with "deflate-frame" protocol extension

    Hello. WebSockets have protocol extension "deflate-frame" for per frame data compression [1]. Webkit and Chrome already support it (see [2] and Chrome sends request header "Sec-WebSocket-Extensions: x-webkit-deflate-frame"). Do you have plans to implement compression in WebSockets?

    [1] http://tools.ietf.org/id/draft-tyoshino-hybi-websocket-perframe-deflate-05.txt [2] http://www.ietf.org/mail-archive/web/hybi/current/msg09463.html

    opened by nilya 12
  • Open event fired before handshake completed on draft76

    Open event fired before handshake completed on draft76

    There is a bug, which happens only for draft76 behind haproxy. It was quite easy to spot it, but here it goes:

    https://github.com/faye/faye-websocket-node/blob/master/lib/faye/websocket.js#L56

      var event = new Event('open');
      event.initEvent('open', false, false);
      this.dispatchEvent(event);
    
      var self = this;
    
      this._stream.addListener('data', function(data) {
        var response = self._parser.parse(data);
        if (!response) return;
        try { self._stream.write(response, 'binary') } catch (e) {}
      });
    

    After the websocket handler sends the handshake, it emits the open event. After that it listens to the data event on the stream. The problem is - handshake may not yet be completed. This can lead to emitting open event prematurely. During the users open handler, there may be some data emitted. This will lead to wrong ordering - user data will be send before the other part of the handshake. This will result in the connection being aborted from the browser (due to bad key).

    opened by majek 10
  • WebSocket client occasionally not receiving first server frame

    WebSocket client occasionally not receiving first server frame

    Apologies in advance for the vagueness of this issue.

    I have observed different client-side behavior between this package and the ws package. In particular, this package seems to sometimes drop or ignore messages sent very shortly after the websocket handshake.

    Here is a minimal repro: https://gist.github.com/ryanpbrewster/6c28751425ec9c10c8e79ae2ded38255

    Here is the output of the repro:

    > node ws.js ws
    connect: 12.882ms ok
    connect: 2.403ms ok
    connect: 2.038ms ok
    connect: 0.979ms ok
    connect: 1.908ms ok
    connect: 2.008ms ok
    connect: 2.256ms ok
    connect: 3.504ms ok
    connect: 2.916ms ok
    connect: 2.741ms ok
    connect: 2.617ms ok
    
    
    
    > node ws.js faye
    connect: 3.512ms ok
    connect: 4.956ms ok
    connect: 4.756ms ok
    connect: 4.125ms ok
    connect: 3.536ms ok
    connect: 2.863ms ok
    connect: 3.763ms ok
    connect: 3.523ms ok
    connect: 3.749ms ok
    connect: 500.985ms timeout
    connect: 6.456ms ok
    connect: 5.415ms ok
    connect: 5.455ms ok
    connect: 4.845ms ok
    

    In short, this example is:

    • start a simple websocket server in the background --- all it does it accept incoming connections, perform the websocket handshake, then immediately try to send a single frame containing "hello"
    • repeatedly create a client, negotiate the websocket handshake, and wait for the first frame from the server

    Occasionally with faye-websocket I observe that the client never receives that initial frame. I cannot reproduce this behavior using a Node.js websocket server, so my initial thought was that it may be a bug in the server implementation. However, the ws module does not seem to have this issue.

    Any insight into why the client sometimes does not receive these frames?

    opened by ryanpbrewster 9
  • No socket close notifications in certain circumstances

    No socket close notifications in certain circumstances

    Okay, related to: https://github.com/faye/faye-websocket-node/issues/54

    I notice I do not get close notifications when I unplug my network cable

    eg:

    'use strict';
    var WebSocket = require("faye-websocket");
    var url = "ws://10.196.46.53:80/websocket";
    var socket = new WebSocket.Client(url, null);
    socket.on("end", function() { console.log("END");});
    socket.on("error", function(error) {console.log("ERROR",error.message);});
    socket.on("close", function(event) {console.log("CLOSE",event.code,event.reason);});
    
    setTimeout(()=>{socket.close();},10000);
    

    If I run this, I get a close notification after 10 seconds. If I unplug my network cable within the 10 seconds of the timeout, I do not get any close or error notification when the timeout is triggered and calls socket.close();

    If I try to do something equivalent with raw sockets, I get:

    var net    = require('net');
    var netOptions = {
        host: '10.196.46.53',
        port: '80'
    };
    var socket = net.connect(netOptions);
    socket.on('error',(err) => {console.log("ERR",err);});
    socket.on('close',(err) => {console.log("CLOSE",err);});
    
    setTimeout(()=>{socket.destroy();},10000);
    
    opened by sebakerckhof 9
  • Support for other tls options such as client cert

    Support for other tls options such as client cert

    https://github.com/faye/faye-websocket-node/blob/067df9aaf45318d273e387251ba115cbdc416ae3/lib/faye/websocket/client.js#L24

    This is unnecessarily restrictive. Please pass on the full options object.

    opened by asilvas 9
  • setTimeout and setNoDelay

    setTimeout and setNoDelay

    The WebSocket constructor should set the socket's timeout and nodelay values to avoid strange behavior:

    ...
    this._stream.setTimeout(0);
    this._stream.setNoDelay(true);
    ...
    
    opened by nicokaiser 8
  • `ws.close()` waits indefinitely

    `ws.close()` waits indefinitely

    This is more a question than an issue.

    Currently when calling ws.close() the server sends a close frame to the client and waits until the client sends back a close frame. If the client doesn't send a close frame and the TCP connection is not closed the ws object is kept alive indefinitely despite having called close() on it.

    This example shows the issue.

    'use strict';
    
    const WebSocket = require('faye-websocket');
    const assert = require('assert');
    const http = require('http');
    const net = require('net');
    
    const server = http.createServer();
    
    server.on('upgrade', (req, socket, head) => {
      const ws = new WebSocket(req, socket, head);
    
      ws.on('message', (evt) => {
        assert.strictEqual(evt.data, '');
        console.log('sending close frame');
        ws.close();
      });
      ws.on('close', (evt) => console.log('close', evt.code, evt.reason));
    });
    
    server.listen(3000, () => {
      const socket = net.connect(3000, () => {
        let handshake = false;
    
        socket.write([
          'GET / HTTP/1.1',
          'Upgrade: websocket',
          'Connection: Upgrade',
          'Sec-WebSocket-Key: rfeGe1izPRq2JyonWunAQw==',
          'Sec-WebSocket-Version: 13',
          '',
          ''
        ].join('\r\n'));
    
        socket.on('data', (data) => {
          if (!handshake) {
            assert.ok(data.equals(Buffer.from([
              'HTTP/1.1 101 Switching Protocols',
              'Upgrade: websocket',
              'Connection: Upgrade',
              'Sec-WebSocket-Accept: prdBmM6el7NzNgJBcdmWum5mTZc=',
              '',
              ''
            ].join('\r\n'))));
    
            handshake = true;
    
            //
            // Send a text frame.
            //
            socket.write(Buffer.from([0x81, 0x80, 0x00, 0x00, 0x00, 0x00]));
            return;
          }
    
          console.log('received close frame');
    
          //
          // This is the close frame.
          //
          assert.ok(data.equals(Buffer.from([0x88, 0x02, 0x03, 0xe8])));
        });
      });
    });
    

    The close event is never emitted.

    I understand this is an edge case and that the client isn't working as expected but is there a clean way to close the connection in such cases? I can only think of using a timer and destroy the socket when it expires:

    const timer = setTimeout(() => ws._stream.destroy(), 15000);
    

    but that seems hacky.

    opened by lpinca 7
  • Update .travis.yml

    Update .travis.yml

    This PR adds CI support for the IBM Power Little Endian (ppc64le) architecture. The idea is to ensure that the builds on this architecture are continuously tested along with the Intel builds (amd64) as this is part of the ubuntu distro on that architecture as well and detecting (and fixing) any issues or failures early would help to ensure that we are always up to date. The build and test results are available at the below location. https://travis-ci.com/github/nageshlop/faye-websocket-node

    opened by nageshlop 6
  • How to handle it when ws.send return false?

    How to handle it when ws.send return false?

    hi, guys, I find that the ws.send API has return a value(true/false) in faye-webosocket-node source code, how should I deal with it? Could be part of the data sent to client(or put into TCP buffer)? How to confirm all the data was sent to client?

    In our server side program, I tried to call ws.send again when ws.send return false, but the client would receive duplicated data sometimes, when I ignored the return false case, sometimes the client would lost data.

    opened by aceway 6
  • Not able to load the library in ESM context using named import

    Not able to load the library in ESM context using named import

    When trying to load the library using and running the script in esm mode:

    import { Client } from 'faye-websocket';
    

    I got an error:

    SyntaxError: Named export 'Client' not found. The requested module 'faye-websocket' is a CommonJS module, which may not support all module.exports as named exports.
    CommonJS modules can always be imported via the default export, for example using:
    
    import pkg from 'faye-websocket';
    const { Client } = pkg;
    

    It suggests a workaround by using the default import first, then destruct the import, but it would be nice for the library to provide an esm entry point using the exports field.

    opened by Feiyang1 1
  • Dangerous example

    Dangerous example

    The example server.js:

    var staticHandler = function(request, response) {
      var path = request.url;
    
      fs.readFile(__dirname + path, function(err, content) {
    

    doesn't validate the url, so there is nothing stopping it from being e.g. /../spec/server.key (given a few lines later). Given that people are likely to copy the example, setting a safe precedent might be a good idea! :-)

    opened by bitdivine 1
  • SSL Pinning with Faye Websockets

    SSL Pinning with Faye Websockets

    I am aware that many websocket libraries in the client-side use faye-websockets to make use of its standards-compliant websocket behaviour. However, those libraries cannot be used to implement SSL pinning (e.g. sockjs-client). Is there any chance that users can implement SSL pinning with faye-websockets? If there is no such official approach, could you please provide any advise for developing such functionality for websockets?

    opened by ashenwgt 2
  • Received WebSocket frames are malformed if fragmented

    Received WebSocket frames are malformed if fragmented

    I've been writing issues starting from NodeJS over to Meteor over to SockJS over to this project now all concerning the same issue and being directed to another project. Hopefully I'm at the end of the rainbow now writing this here. The issue is as follows:

    I'm sending websockets over to a meteor app (which uses SockJS which uses faye-websocket apparently). One of the frames is fragmented over two TCP packets. This results in the websocket being closed due to an unknown opcode (13). Here's the wireshark dump of the communication:

    http://p.jreinert.com/yM9/

    opened by repomaa 9
Owner
null
A node.js module for websocket server and client

Nodejs Websocket A nodejs module for websocket server and client How to use it Install with npm install nodejs-websocket or put all files in a folder

Guilherme Souza 719 Dec 13, 2022
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 2.1k Dec 29, 2022
This Repository implements an Authenticated Websocket Server built in Node Js along ws library.

websockets-authentication-server This Repository implements an Authenticated Websocket Server built in Node Js along ws library. Features Authenticate

M.Abdullah Ch 7 May 5, 2023
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 70 Dec 23, 2022
A WebSocket Implementation for Node.JS (Draft -08 through the final RFC 6455)

WebSocket Client & Server Implementation for Node Overview This is a (mostly) pure JavaScript implementation of the WebSocket protocol versions 8 and

Brian McKelvey 3.6k Dec 30, 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 Jan 2, 2023
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 Jan 2, 2023
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 21 Dec 28, 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
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 23 Dec 6, 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 12 Dec 3, 2022
🚀🚀🚀 Nuxt3 client and server communication

Nuxt 3 Minimal Starter Look at the nuxt 3 documentation to learn more. Setup Make sure to install the dependencies: # yarn yarn install # npm npm ins

HomWang 4 Dec 19, 2022
🔄 iola: Socket client with REST API

?? iola: Socket client with REST API

Pavel Varentsov 113 Jan 3, 2023
soketi is your simple, fast, and resilient open-source WebSockets server

soketi soketi is your simple, fast, and resilient open-source WebSockets server. ?? Blazing fast speed âš¡ The server is built on top of uWebSockets.js

Soketi 3.2k Jan 4, 2023
This server is made to serve the MSN-Messenger app develop by Gabriel Godoy. This applications is capable to register users and messages in order implements a real time chat.

?? MSN-Messenger-Server Node.js server for real time chat About | Installations | How to Use | Documentation | Technologies | License ?? About This se

Guilherme Feitosa 7 Dec 20, 2022
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
Super-Resolution-CNN - web server for super-resolution CNN

Web Server for Image Super-Resolution This project showcases the Super-Resolution CNN (SRCNN). The model is pretrained following this tutorial. The or

Daniel O'Sullivan 1 Jan 3, 2022