# A WebSocket Server in Node.js with ws — WebSockets & Server-Sent Events

Source: https://www.skillbyai.com/en/realtime-web/rt-ws-node

> Build an echo server with the ws library and connect to it with Node's built-in WebSocket client.

## Why ws, and how it is shaped

Node.js includes a browser-compatible **WebSocket client** as a global in current versions, but no WebSocket **server**. The widely used `ws` package fills that gap with a small, fast implementation that does not invent its own protocol. A `WebSocketServer` either listens on its own port or attaches to an existing HTTP server, which is what you do in real apps so HTTP routes and WebSockets share a port. It emits `connection` with a socket per client. Each socket emits `message` with a `Buffer` (or array of buffers) and an `isBinary` flag, so convert text with `toString()` or a template string. `wss.clients` is a `Set` of connected sockets, handy for broadcasting. Important options include `maxPayload` (reject huge messages, default 100 MiB, usually far too generous), `perMessageDeflate` (compression, off by default because it costs memory and CPU per connection) and `noServer` for handling the upgrade yourself.

## Echo server plus client in one file

The server echoes text with a prefix; the client sends one message and closes with 1000. Run with `node echo.mjs` after `npm install ws`.

```js
import { WebSocketServer } from 'ws';

const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', (socket) => {
  console.log('server: client connected');
  socket.on('message', (data, isBinary) => {
    socket.send(isBinary ? data : `echo: ${data}`);
  });
  socket.on('close', (code, reason) => {
    console.log('server: closed', code, reason.toString());
  });
});

wss.on('listening', () => {
  // Node 22+ ships a browser-compatible WebSocket client as a global.
  const ws = new WebSocket('ws://localhost:8080');
  ws.addEventListener('open', () => ws.send('namaste'));
  ws.addEventListener('message', (event) => {
    console.log('client got:', event.data);
    ws.close(1000, 'done');
  });
  ws.addEventListener('close', (event) => {
    console.log('client: close event', event.code, event.wasClean);
    wss.close();
  });
});
```

Output:

```
server: client connected
client got: echo: namaste
client: close event 1000 true
server: closed 1000 done
```

## Attach to your HTTP server in real apps

Use `new WebSocketServer({ server: httpServer })` or `noServer: true` with the HTTP server's `upgrade` event. One port means one TLS certificate, one load-balancer rule, and the ability to check cookies or tokens before accepting the upgrade.

## A hotel reception desk

The `WebSocketServer` is the reception desk; each `connection` hands you a room key for one guest. After check-in, you talk to the guest through their room phone (the socket) and never go back to reception for that guest again.

**Quiz:** In ws, why does the message handler often call `data.toString()`?

- [ ] Because ws only supports binary frames
- [x] Because messages arrive as Buffer objects, even for text frames
- [ ] To decompress the payload
- [ ] To unmask the frame

*Answer:* Because messages arrive as Buffer objects, even for text frames. ws delivers payloads as Buffers and passes an `isBinary` flag. Text must be decoded, for example with `toString()` or a template literal.
