WebSocket Library for Node.js

8.20.0 · active · verified Sun Apr 19

`ws` is a highly performant, thoroughly tested WebSocket client and server implementation designed specifically for Node.js environments. As of version 8.20.0, it provides robust support for the WebSocket protocol, including the permessage-deflate extension for compression and passing the extensive Autobahn test suite. It differentiates itself through its focus on speed, reliability, and full protocol compliance in Node.js. `ws` maintains an active release cadence, frequently addressing bug fixes, performance improvements, and minor features. It's crucial to note that `ws` is intended for backend Node.js applications; browser-based WebSocket clients should use the native `WebSocket` API or a wrapper like `isomorphic-ws`. The library offers both server and client capabilities, allowing Node.js to act as either endpoint in WebSocket communication.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to set up a basic `ws` WebSocket server listening on an HTTP port, handle incoming messages, and how to connect to it using a `ws` client, sending and receiving text data.

import { WebSocketServer, WebSocket } from 'ws';
import * as http from 'http';

// Create a simple HTTP server to attach the WebSocket server to
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('WebSocket server is running\n');
});

const wss = new WebSocketServer({ server });

wss.on('connection', function connection(ws) {
  console.log('Client connected');

  ws.on('message', function message(data, isBinary) {
    const message = isBinary ? data : data.toString();
    console.log('Received:', message);

    // Echo the message back to the client
    ws.send(`Echo: ${message}`);
  });

  ws.on('close', () => {
    console.log('Client disconnected');
  });

  ws.on('error', (error) => {
    console.error('WebSocket error:', error);
  });

  ws.send('Welcome to the WebSocket server!');
});

server.listen(8080, () => {
  console.log('HTTP and WebSocket server listening on http://localhost:8080');

  // Example client connecting to the server
  const client = new WebSocket('ws://localhost:8080');

  client.onopen = () => {
    console.log('Client connected to WebSocket server');
    client.send('Hello from client!');
  };

  client.onmessage = (event) => {
    console.log('Client received:', event.data);
    client.close(); // Close after receiving an echo
  };

  client.onerror = (error) => {
    console.error('Client WebSocket error:', error);
  };

  client.onclose = () => {
    console.log('Client disconnected');
    server.close(); // Close the server after client disconnects
  };
});

view raw JSON →