Product
Introducing License Enforcement in Socket
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
websocket-driver
Advanced tools
The websocket-driver npm package provides a low-level interface for implementing WebSocket clients and servers according to the WebSocket protocol. It is designed to work in any JavaScript environment, including Node.js and browsers, making it versatile for developing real-time, bidirectional communication applications.
Creating a WebSocket server
This code sample demonstrates how to create a WebSocket server that listens for connections, receives messages from clients, and sends a response back. It uses the `websocket-driver` package to handle the WebSocket protocol.
const http = require('http');
const WebSocketDriver = require('websocket-driver');
const server = http.createServer();
server.on('upgrade', function(request, socket, body) {
if (!WebSocketDriver.isWebSocket(request)) return;
var driver = WebSocketDriver.http(request);
driver.on('connect', function() {
driver.start();
});
driver.on('message', function(e) {
console.log('Received message:', e.data);
driver.text('Hello from server');
});
driver.on('close', function(e) {
console.log('Client disconnected');
});
driver.parse(body);
});
server.listen(3000);
Creating a WebSocket client
This code sample shows how to create a WebSocket client that connects to a server, sends a message, and handles incoming messages and the closing of the connection. It utilizes the `websocket-driver` package for managing the WebSocket connection.
const WebSocketDriver = require('websocket-driver');
const driver = WebSocketDriver.client('ws://www.example.com/socket');
driver.on('open', function() {
console.log('Connection opened');
driver.text('Hello from client');
});
driver.on('message', function(e) {
console.log('Received message:', e.data);
});
driver.on('close', function(e) {
console.log('Connection closed');
});
driver.start();
The 'ws' package is a popular WebSocket library for Node.js that provides a simple interface for creating WebSocket servers and clients. It is more high-level compared to 'websocket-driver', offering built-in features like automatic reconnection, which might not be directly available in 'websocket-driver'.
While 'socket.io' is not a pure WebSocket library, it provides real-time bidirectional event-based communication using WebSocket as the transport mechanism when possible. It falls back to other methods for older browsers. 'socket.io' is more feature-rich, offering rooms, namespaces, and middleware support, making it suitable for more complex applications compared to 'websocket-driver'.
The 'faye-websocket' package is another WebSocket library for both Node.js and browser environments. It is similar to 'websocket-driver' in providing low-level WebSocket protocol support. However, 'faye-websocket' is part of the larger Faye project, which includes a messaging system and server, offering a broader scope of functionality.
This module provides a complete implementation of the WebSocket protocols that can be hooked up to any I/O stream. It aims to simplify things by decoupling the protocol details from the I/O layer, such that users only need to implement code to stream data in and out of it without needing to know anything about how the protocol actually works. Think of it as a complete WebSocket system with pluggable I/O.
Due to this design, you get a lot of things for free. In particular, if you hook this module up to some I/O object, it will do all of this for you:
Sec-WebSocket-Protocol
This library was originally extracted from the Faye project but now aims to provide simple WebSocket support for any Node-based project.
$ npm install websocket-driver
This module provides protocol drivers that have the same interface on the server and on the client. A WebSocket driver is an object with two duplex streams attached; one for incoming/outgoing messages and one for managing the wire protocol over an I/O stream. The full API is described below.
A Node webserver emits a special event for 'upgrade' requests, and this is where you should handle WebSockets. You first check whether the request is a WebSocket, and if so you can create a driver and attach the request's I/O stream to it.
var http = require('http'),
websocket = require('websocket-driver');
var server = http.createServer();
server.on('upgrade', function(request, socket, body) {
if (!websocket.isWebSocket(request)) return;
var driver = websocket.http(request);
driver.io.write(body);
socket.pipe(driver.io);
driver.io.pipe(socket);
driver.messages.on('data', function(message) {
console.log('Got a message', message);
});
driver.start();
};
Note the line driver.io.write(body)
- you must pass the body
buffer to the
socket driver in order to make certain versions of the protocol work.
Similarly, to implement a WebSocket client you just need to make a driver by passing in a URL. After this you use the driver API as described below to process incoming data and send outgoing data.
var net = require('net'),
websocket = require('websocket-driver');
var driver = websocket.client('ws://www.example.com/socket'),
tcp = net.createConnection(80, 'www.example.com');
tcp.pipe(driver.io);
driver.io.pipe(tcp);
driver.messages.on('data', function(message) {
console.log('Got a message', message);
});
tcp.on('connect', function() {
driver.start();
});
Drivers are created using one of the following methods:
driver = websocket.http(request, options)
driver = websocket.client(url, options)
The http
method returns a driver chosen using the headers from a Node HTTP
request object. The client
method always returns a driver for the RFC version
of the protocol with masking enabled on outgoing frames.
The options
argument is optional, and is an object. It may contain the
following fields:
protocols
- an array of strings representing acceptable subprotocols for
use over the socket. The driver will negotiate one of these to use via the
Sec-WebSocket-Protocol
header if supported by the other peer.A driver has two duplex streams attached to it:
driver.io
- this stream should be attached to an I/O socket like a
TCP stream. Pipe incoming TCP chunks to this stream for them to be parsed,
and pipe this stream back into TCP to send outgoing frames.driver.messages
- this stream emits messages received over the
WebSocket. Writing to it sends messages to the other peer by emitting frames
via the driver.io
stream.All drivers respond to the following API methods, but some of them are no-ops depending on whether the client supports the behaviour.
Note that most of these methods are commands: if they produce data that should
be sent over the socket, they will give this to you by emitting data
events
on the driver.io
stream.
driver.on('open', function(event) {})
Sets the callback to execute when the socket becomes open.
driver.on('message', function(event) {})
Sets the callback to execute when a message is received. event
will have a
data
attribute containing either a string in the case of a text message or a
Buffer
in the case of a binary message.
You can also listen for messages using the driver.messages.on('data')
event,
which emits strings for text messages and buffers for binary messages.
driver.on('error', function(event) {})
Sets the callback to execute when a protocol error occurs due to the other peer
sending an invalid byte sequence. event
will have a message
attribute
describing the error.
driver.on('close', function(event) {})
Sets the callback to execute when the socket becomes closed. The event
object
has code
and reason
attributes.
driver.start()
Initiates the protocol by sending the handshake - either the response for a
server-side driver or the request for a client-side one. This should be the
first method you invoke. Returns true
iff a handshake was sent.
driver.parse(string)
Takes a string and parses it, potentially resulting in message events being
emitted (see on('message')
above) or in data being sent to driver.io
. You
should send all data you receive via I/O to this method by piping a stream into
driver.io
.
driver.text(string)
Sends a text message over the socket. If the socket handshake is not yet
complete, the message will be queued until it is. Returns true
if the message
was sent or queued, and false
if the socket can no longer send messages.
This method is equivalent to driver.messages.write(string)
.
driver.binary(buffer)
Takes a Buffer
and sends it as a binary message. Will queue and return true
or false
the same way as the text
method. It will also return false
if
the driver does not support binary messages.
This method is equivalent to driver.messages.write(buffer)
.
driver.ping(string = '', function() {})
Sends a ping frame over the socket, queueing it if necessary. string
and the
callback are both optional. If a callback is given, it will be invoked when the
socket receives a pong frame whose content matches string
. Returns false
if
frames can no longer be sent, or if the driver does not support ping/pong.
driver.close()
Initiates the closing handshake if the socket is still open. For drivers with
no closing handshake, this will result in the immediate execution of the
on('close')
driver. For drivers with a closing handshake, this sends a
closing frame and emit('close')
will execute when a response is received or a
protocol error occurs.
driver.version
Returns the WebSocket version in use as a string. Will either be hixie-75
,
hixie-76
or hybi-$version
.
driver.protocol
Returns a string containing the selected subprotocol, if any was agreed upon
using the Sec-WebSocket-Protocol
mechanism. This value becomes available
after emit('open')
has fired.
(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.
0.1.0 / 2013-05-04
FAQs
WebSocket protocol handler with pluggable I/O
The npm package websocket-driver receives a total of 12,024,937 weekly downloads. As such, websocket-driver popularity was classified as popular.
We found that websocket-driver 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.
Product
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
Product
We're launching a new set of license analysis and compliance features for analyzing, managing, and complying with licenses across a range of supported languages and ecosystems.
Product
We're excited to introduce Socket Optimize, a powerful CLI command to secure open source dependencies with tested, optimized package overrides.