WebSocket client and server for Node.js. Implements RFC 6455 and RFC 7692.
const WebSocket = require('presidium-websocket')
const server = new WebSocket.Server(websocket => {
websocket.on('message', message => {
console.log('Message from client:', message)
websocket.send('Hello from server!')
})
websocket.on('close', () => {
console.log('websocket closed')
})
})
server.listen(1337, () => {
console.log('WebSocket server listening on port 1337')
})
const websocket = new WebSocket('ws://localhost:1337/')
websocket.on('open', () => {
websocket.send('Hello from client!')
})
websocket.on('message', message => {
console.log('Message from server:', message)
})
Serve WebSocket Secure (WSS) connections.
const WebSocket = require('presidium-websocket')
const fs = require('fs')
const server = new WebSocket.SecureServer({
key: fs.readFileSync('/path/to/my-key'),
cert: fs.readFileSync('/path/to/my-cert')
})
server.on('connection', websocket => {
websocket.on('message', message => {
console.log('Secure message from client:', message)
websocket.send('Hello from server!')
})
websocket.on('close', () => {
console.log('websocket closed')
})
})
server.listen(4443, () => {
console.log('WebSocket Secure server listening on port 4443')
})
const websocket = new WebSocket('wss://localhost:4443/')
websocket.on('open', () => {
websocket.send('Hello from client!')
})
websocket.on('message', message => {
console.log('Message from server:', message)
})
Supports Compression Extensions for WebSocket with supportPerMessageDeflate
(uses zlib default options).
const server = new WebSocket.Server({ supportPerMessageDeflate: true })
Initiate new connections on the same websocket instance.
const websocket = new WebSocket('ws://localhost:1337/')
// reconnect websocket on broken connections
while (true) {
if (websocket.readyState === 1) {
// websocket is open
} else {
// reconnect
websocket.connect()
}
await sleep(10000)
}
with npm:
npm i presidium-websocket
Constructs a Presidium WebSocket client.
new WebSocket(url string) -> websocket WebSocket
new WebSocket(url string, options {
rejectUnauthorized: boolean,
autoConnect: boolean,
maxMessageLength: number,
socketBufferLength: number,
offerPerMessageDeflate: boolean
}) -> websocket WebSocket
Options:
rejectUnauthorized
- iftrue
, the client verifies the server's certificate against a list of pre-approved certificate authorities (CAs). An error event is emitted if verification fails;err.code
contains the OpenSSL error code. Defaults totrue
.autoConnect
- iftrue
, establishes the underlying TCP connection automatically upon construction. Defaults totrue
.maxMessageLength
- the maximum length in bytes of sent messages. If a message is longer thanmaxMessageLength
, it is split into fragmented messages that are reassembled by the receiver.socketBufferLength
- length in bytes of the internal buffer of the underlying socket.offerPerMessageDeflate
- iftrue
, offers to the server Per-Message Compression Extensions by including theSec-WebSocket-Extensions: permessage-deflate
header in the initial WebSocket handshake. If the server supports compression extensions, all messages exchanged in the WebSocket connection will be compressed with zlib default options. Defaults totrue
.
Events:
Methods:
- websocket.send
- websocket.sendClose
- websocket.sendPing
- websocket.sendPong
- websocket.close
- websocket.destroy
Attributes:
Emitted when the WebSocket protocol handshake is complete.
websocket.on('open', ()=>()) -> ()
Ensure the WebSocket connection is open before sending messages.
const server = new WebSocket.Server()
server.on('connection', websocket => {
websocket.on('open', () => {
websocket.send('server-message-1')
websocket.send('server-message-2')
websocket.send('server-message-3')
})
})
server.listen(1337)
const websocket = new WebSocket('ws://localhost:1337/')
websocket.on('open', () => {
websocket.send('client-message-1')
websocket.send('client-message-2')
websocket.send('client-message-3')
})
Emitted upon receipt and successful decoding (and reassembly, if applicable) of an incoming message.
websocket.on('message', (message Buffer)=>()) -> ()
Emitted upon receipt and successful decoding of an incoming "ping" message.
websocket.on('ping', (payload Buffer)=>()) -> ()
Emitted upon receipt and successful decoding of an incoming "pong" message.
websocket.on('pong', (payload Buffer)=>()) -> ()
Emitted if an error occurs on the WebSocket instance or on the underlying socket.
websocket.on('error', (error Error)=>()) -> ()
Emitted when the underlying socket is destroyed. The 'close'
event can be emitted after a call to the websocket.close method.
websocket.on('close', ()=>()) -> ()
Initiates a new connection to the WebSocket server.
websocket.connect() -> ()
Sends a payload to the WebSocket server.
websocket.send(payload Buffer|string) -> ()
Sends a close frame to the WebSocket server.
websocket.sendClose() -> ()
websocket.sendClose(payload Buffer|string) -> ()
Sends a ping frame to the server.
websocket.sendPing() -> ()
websocket.sendPing(payload Buffer|string) -> ()
Sends a pong frame to the server.
websocket.sendPong() -> ()
websocket.sendPong(payload Buffer|string) -> ()
Closes the connection to the WebSocket server.
websocket.close() -> ()
websocket.close(payload Buffer|string) -> ()
Destroys the underlying socket.
websocket.destroy() -> ()
websocket.destroy(payload Buffer|string) -> ()
Indicates the current state of the WebSocket connection.
websocket.readyState -> 0|1|2|3
Values:
0
- "CONNECTING" - the socket been created, but the connection is not yet open.1
- "OPEN" - the connection is ready to send and receive data.2
- "CLOSING" - the connection is in the process of closing.3
- "CLOSED" - the connection is closed or couldn't be opened.
Constructs a Presidium WebSocket server.
module http 'https://nodejs.org/api/http.html'
module net 'https://nodejs.org/api/net.html'
type WebSocketHandler = (websocket WebSocket)=>()
type HTTPHandler = (request http.ClientRequest, response http.ServerResponse)=>()
new WebSocket.Server() -> server WebSocket.Server
new WebSocket.Server(websocketHandler WebSocketHandler) -> server WebSocket.Server
new WebSocket.Server(websocketHandler WebSocketHandler, options {
httpHandler: HTTPHandler,
secure: boolean,
key: string|Array<string>|Buffer|Array<Buffer>|Array<{
pem: string|Buffer,
passphrase: string
}>,
cert: string|Array<string>|Buffer|Array<Buffer>,
passphrase: string,
supportPerMessageDeflate: boolean,
maxMessageLength: number,
socketBufferLength: number
}) -> server WebSocket.Server
new WebSocket.Server(options {
websocketHandler: WebSocketHandler,
httpHandler: HTTPHandler,
secure: boolean,
key: string|Array<string>|Buffer|Array<Buffer>|Array<{
pem: string|Buffer,
passphrase: string
}>,
cert: string|Array<string>|Buffer|Array<Buffer>,
passphrase: string,
supportPerMessageDeflate: boolean,
maxMessageLength: number,
socketBufferLength: number
}) -> server WebSocket.Server
Options:
httpHandler
- function that processes incoming HTTP requests from clients. Defaults to an HTTP handler that responds with200 OK
.secure
- iftrue
, starts an HTTPS server instead of an HTTP server. Clients must connect to the server using thewss
protocol instead of thews
protocol. Requireskey
andcert
options.key
- private key(s) in PEM format. Encrypted keys will be decrypted using thepassphrase
option. Multiple keys using different algorithms can be provided as an array of unencrypted key strings or buffers, or an array of objects in the form{ pem: string|Buffer, passphrase: string }
.cert
- cert chain(s) in PEM format. One cert chain should be provided per private key.passphrase
- used to decrypt the private key(s).supportPerMessageDeflate
- iftrue
, indicates to WebSocket clients that the server supports Compression Extensions for WebSocket. If an incoming WebSocket connection has requested compression extensions via theSec-WebSocket-Extensions: permessage-deflate
header, all messages exchanged in the WebSocket connection will be compressed using zlib default options. Defaults tofalse
.maxMessageLength
- the maximum length in bytes of sent messages. If a message is longer thanmaxMessageLength
, it is split into fragmented messages that are reassembled by the receiver.socketBufferLength
- length in bytes of the internal buffer of the underlying socket for all connections to the server.
Events:
Methods:
Attributes:
Emitted when a new WebSocket connection is made to the server.
server.on('connection', (websocket WebSocket) => {
websocket.on('open', ()=>()) -> ()
websocket.on('message', (message Buffer)=>()) -> ()
websocket.on('ping', (payload Buffer)=>()) -> ()
websocket.on('pong', (payload Buffer)=>()) -> ()
websocket.on('error', (error Error)=>()) -> ()
websocket.on('close', ()=>()) -> ()
websocket.send(payload Buffer|string) -> ()
websocket.sendClose(payload Buffer|string) -> ()
websocket.sendPing(payload Buffer|string) -> ()
websocket.sendPong(payload Buffer|string) -> ()
websocket.close() -> ()
websocket.destroy() -> ()
})
See WebSocket.
Emitted on each HTTP request to the server.
module http 'https://nodejs.org/api/http.html'
type HTTPHandler = (request http.ClientRequest, response http.ServerResponse)=>()
server.on('request', httpHandler HTTPHandler) -> ()
Emitted when a client requests an HTTP upgrade.
module http 'https://nodejs.org/api/http.html'
module net 'https://nodejs.org/api/net.html'
type UpgradeHandler = (request http.ClientRequest, socket net.Socket, head Buffer)=>()
server.on('upgrade', upgradeHandler UpgradeHandler) -> ()
Emitted when the server's close method is called.
server.on('close', ()=>()) -> ()
Starts the server listening for connections.
server.listen(port number) -> ()
server.listen(port number, callback ()=>()) -> ()
server.listen(port number, host string, callback ()=>()) -> ()
server.listen(port number, backlog number, callback ()=>()) -> ()
server.listen(port number, host string, backlog number, callback ()=>()) -> ()
Arguments:
port
- the network port on which the server is listening.host
- the ip address of the network device on which the server is running. Defaults to the 0.0.0.0.backlog
- a number that specifies the maximum length of the queue of pending connections. Defaults to 511.callback
- a function that is called when the server has started listening.
Stops the server from accepting new connections and closes all current connections.
server.close() -> ()
server.close(callback ()=>()) -> ()
An array of WebSocket client connections to the server.
server.connections -> Array<WebSocket>
Constructs a Presidium WebSocket Secure (WSS) server.
module http 'https://nodejs.org/api/http.html'
module net 'https://nodejs.org/api/net.html'
type WebSocketHandler = (websocket WebSocket)=>()
type HTTPHandler = (request http.ClientRequest, response http.ServerResponse)=>()
new WebSocket.SecureServer(websocketHandler WebSocketHandler, options {
httpHandler: HTTPHandler,
key: string|Array<string>|Buffer|Array<Buffer>|Array<{
pem: string|Buffer,
passphrase: string
}>,
cert: string|Array<string>|Buffer|Array<Buffer>,
passphrase: string,
supportPerMessageDeflate: boolean,
maxMessageLength: number
socketBufferLength: number
}) -> server WebSocket.SecureServer
new WebSocket.SecureServer(options {
websocketHandler: WebSocketHandler,
httpHandler: HTTPHandler,
key: string|Array<string>|Buffer|Array<Buffer>|Array<{
pem: string|Buffer,
passphrase: string
}>,
cert: string|Array<string>|Buffer|Array<Buffer>,
passphrase: string,
supportPerMessageDeflate: boolean,
maxMessageLength: number
socketBufferLength: number
}) -> server WebSocket.SecureServer
Options:
httpHandler
- function that processes incoming HTTP requests from clients. Defaults to an HTTP handler that responds with200 OK
.key
- private key(s) in PEM format. Encrypted keys will be decrypted using thepassphrase
option. Multiple keys using different algorithms can be provided as an array of unencrypted key strings or buffers, or an array of objects in the form{ pem: string|Buffer, passphrase: string }
.cert
- cert chain(s) in PEM format. One cert chain should be provided per private key.passphrase
- used to decrypt the private key(s).supportPerMessageDeflate
- iftrue
, indicates to WebSocket clients that the server supports Compression Extensions for WebSocket. If an incoming WebSocket connection has requested compression extensions via theSec-WebSocket-Extensions: permessage-deflate
header, all messages exchanged in the WebSocket connection will be compressed using zlib default options. Defaults tofalse
.maxMessageLength
- the maximum length in bytes of sent messages. If a message is longer thanmaxMessageLength
, it is split into fragmented messages that are reassembled by the receiver.socketBufferLength
- length in bytes of the internal buffer of the underlying socket for all connections to the server.
Events:
Methods:
Stats for 30 individual 30s runs of bench-presidium and bench-ws with a small (16 byte) buffer:
OS 6.15.4-arch2-1
Node.js v22.12.0
[email protected]
[email protected]
Presidium Max Throughput: 773.9204074888052
Presidium Min Throughput: 663.717446247961
Presidium Avg Throughput: 740.4098268048717
ws Max Throughput: 734.9618854401924
ws Min Throughput: 699.1601014862653
ws Avg Throughput: 721.359269165629
Single run results of bench-presidium and bench-ws with a large (3MB) buffer:
OS 6.15.4-arch2-1
Node.js v22.12.0
[email protected]
[email protected]
Time: 30.561878826 seconds
Presidium throughput: 30.706097880478325 messages/s
Presidium messages: 937
Time: 30.536667375 seconds
ws throughput: 32.7349797644342 messages/s
ws messages: 998
Please find all of the published benchmark output inside the benchmark-output folder.
Run benchmarks for ws:
./bench-ws
Run benchmarks for presidium-websocket:
./bench-presidium
Your feedback and contributions are welcome. If you have a suggestion, please raise an issue. Prior to that, please search through the issues first in case your suggestion has been made already. If you decide to work on an issue, please create a pull request.
Pull requests should provide some basic context and link the relevant issue. Here is an example pull request. If you are interested in contributing, the help wanted tag is a good place to start.
For more information please see CONTRIBUTING.md
Presidium WebSocket is MIT Licensed.
- minimum Node.js version: 16