Gathering detailed insights and metrics for faye-websocket
Gathering detailed insights and metrics for faye-websocket
Gathering detailed insights and metrics for faye-websocket
Gathering detailed insights and metrics for faye-websocket
Standards-compliant WebSocket client and server
npm install faye-websocket
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
610 Stars
314 Commits
102 Forks
31 Watching
5 Branches
11 Contributors
Updated on 19 Nov 2024
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-5%
3,361,342
Compared to previous day
Last week
2.8%
17,948,751
Compared to previous week
Last month
14.7%
73,656,859
Compared to previous month
Last year
-2.2%
798,235,458
Compared to previous year
1
3
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.
$ npm install faye-websocket
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:
1var WebSocket = require('faye-websocket'), 2 http = require('http'); 3 4var server = http.createServer(); 5 6server.on('upgrade', function(request, socket, body) { 7 if (WebSocket.isWebSocket(request)) { 8 var ws = new WebSocket(request, socket, body); 9 10 ws.on('message', function(event) { 11 ws.send(event.data); 12 }); 13 14 ws.on('close', function(event) { 15 console.log('close', event.code, event.reason); 16 ws = null; 17 }); 18 } 19}); 20 21server.listen(8000);
WebSocket
objects are also duplex streams, so you could replace the
ws.on('message', ...)
line with:
1 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
.
1ws.ping('Mic check, one, two', function() { 2 // fires when pong is received 3});
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
.
1var WebSocket = require('faye-websocket'), 2 ws = new WebSocket.Client('ws://www.example.com/'); 3 4ws.on('open', function(event) { 5 console.log('open'); 6 ws.send('Hello, world!'); 7}); 8 9ws.on('message', function(event) { 10 console.log('message', event.data); 11}); 12 13ws.on('close', function(event) { 14 console.log('close', event.code, event.reason); 15 ws = null; 16});
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.
1var ws = new WebSocket.Client('ws://www.example.com/', [], {
2 proxy: {
3 origin: 'http://username:password@proxy.example.com',
4 headers: { 'User-Agent': 'node' },
5 tls: { cert: fs.readFileSync('client.crt') }
6 }
7});
The tls
value is an object that will be passed to
tls.connect()
.
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:
1var 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:
1var 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.
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:
1var deflate = require('permessage-deflate'); 2 3var ws = new WebSocket(request, socket, body, [], { extensions: [deflate] });
Both the server- and client-side classes allow an options object to be passed in at initialization time, for example:
1var ws = new WebSocket(request, socket, body, protocols, options);
2var 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 aboveheaders
- an object containing key-value pairs representing HTTP headers to
be sent during the handshake processmaxLength
- 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 secondsThe client accepts some additional options:
proxy
- settings for a proxy as described abovenet
- 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 } }
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.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.
1var WebSocket = require('faye-websocket'), 2 EventSource = WebSocket.EventSource, 3 http = require('http'); 4 5var server = http.createServer(); 6 7server.on('request', function(request, response) { 8 if (EventSource.isEventSource(request)) { 9 var es = new EventSource(request, response); 10 console.log('open', es.url, es.lastEventId); 11 12 // Periodically send messages 13 var loop = setInterval(function() { es.send('Hello') }, 1000); 14 15 es.on('close', function() { 16 clearInterval(loop); 17 es = null; 18 }); 19 20 } else { 21 // Normal HTTP request 22 response.writeHead(200, { 'Content-Type': 'text/plain' }); 23 response.end('Hello'); 24 } 25}); 26 27server.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
:
1es.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:
1var es = new EventSource(request, response, {
2 headers: { 'Access-Control-Allow-Origin': '*' },
3 ping: 15,
4 retry: 10
5});
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.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
Found 2/29 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More