Security News
PyPI Introduces Digital Attestations to Strengthen Python Package Security
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
faye-websocket
Advanced tools
The faye-websocket npm package is a WebSocket client and server implementation that allows you to build real-time web applications. It provides an easy-to-use API for handling WebSocket connections and messages.
WebSocket Client
This code sample demonstrates how to create a WebSocket client that connects to a server, sends a message, and listens for messages and the close event.
const WebSocket = require('faye-websocket');
const ws = new WebSocket.Client('ws://www.example.com/');
ws.on('open', function(event) {
console.log('Connection established');
ws.send('Hello, world!');
});
ws.on('message', function(event) {
console.log('Received message: ' + event.data);
});
ws.on('close', function(event) {
console.log('Connection closed', event.code, event.reason);
ws = null;
});
WebSocket Server
This code sample shows how to set up a WebSocket server that can accept connections, echo received messages back to the client, and handle the close event.
const http = require('http');
const WebSocket = require('faye-websocket');
const server = http.createServer();
server.on('upgrade', function(request, socket, body) {
if (WebSocket.isWebSocket(request)) {
const ws = new WebSocket(request, socket, body);
ws.on('message', function(event) {
ws.send(event.data);
});
ws.on('close', function(event) {
console.log('Connection closed', event.code, event.reason);
ws = null;
});
}
});
server.listen(3000);
The 'ws' package is a popular WebSocket implementation for Node.js. It is similar to faye-websocket but is more widely used and actively maintained. It offers a simpler interface for WebSocket communication and is known for its performance and compliance with the WebSocket protocol.
Socket.IO is a library that enables real-time, bidirectional and event-based communication between web clients and servers. It is more feature-rich than faye-websocket, providing fallbacks for older browsers, automatic reconnection, and a higher-level event-driven API.
The 'websocket' package provides both client and server-side implementations of the WebSocket protocol. It is similar to faye-websocket but offers additional features such as WebSocket extensions and a wider range of subprotocols.
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:
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);
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
iff 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
});
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 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.
Both server- and client-side WebSocket
objects support the following API.
They are both readable and writable streams, so for example you can write an
echo server using socket.pipe(socket)
.
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.
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:
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 pings every 15 seconds and is retryable every 10 seconds if the connection is broken:
var es = new EventSource(request, response, {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.
(The MIT License)
Copyright (c) 2010-2013 James Coglan
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
FAQs
Standards-compliant WebSocket server and client
We found that faye-websocket demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.