ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and server JavaScript implementation.
ws: a Node.js WebSocket library
WebSockets represent a long awaited evolution in client/server technology. They allow a single TCP socket connection to be established between the client and server which allows for bi-directional messages to be distributed with little overhead resulting in a low latency connection.
ws
allows to easily implement this protocol on Node applications, both for WebSocket servers and WebSocket clients. This module is not suited for browser apps, which must use the native WebSocket
object; the client WebSocket capabilities are designed for Node applications with the role of a client.
Resources
- NPM homepage
- Github homepage
- Flavio Copes' guide on WebSockets, using the
ws
package for Node code
Example
// index.js
const WebSocket = require('ws');
// server code
const wsServer = new WebSocket.Server({port: 8080});
wsServer.on('connection', serverSocket => {
console.log('server: new connection');
serverSocket.onopen = evt => console.log('server: open');
serverSocket.onmessage = evt => console.log('server: message:', evt.data);
serverSocket.onclose = evt => console.log('server: close');
setTimeout(() => serverSocket.send('Hello from server'), 1000);
setTimeout(() => serverSocket.close(), 3000);
});
// client code
const clientSocket = new WebSocket('ws://localhost:8080');
clientSocket.onopen = evt => console.log('client: open');
clientSocket.onmessage = evt => console.log('client: message:', evt.data);
clientSocket.onclose = evt => console.log('client: close');
setTimeout(() => clientSocket.send('Hello from client'), 2000);
Commented standard output of node index.js
:
# t=0s
server: new connection
client: open
# t=1s
client: message: Hello from server
# t=2s
server: message: Hello from client
# t=3s
server: close
client: close