WebSocket server
- Node.js course
- Advanced
- Lesson 38/83
- 5 min
Learn to set up a server with new WebSocket.Server.
WebSocket server
Creating a WebSocket server: const wss = new WebSocketServer({ port: 8080 }). This starts a server listening on port 8080. Clients connect to ws://host:8080.
The server listens for connection events. wss.on("connection", (ws) => { ... }) fires on each new client. The ws parameter represents the client connection. You catch messages with ws.on("message", cb) and send with ws.send(data). To close the server call wss.close().
The noServer option
Sometimes you want to attach the WebSocket server to your own HTTP server. The { noServer: true } option does this. Instead of its own port, the server listens to the HTTP server's 'upgrade' event.
This pattern is common for running Express and WebSocket on the same port. server.on("upgrade", (req, socket, head) => { wss.handleUpgrade(req, socket, head, (ws) => { ... }); }). This serves both HTTP and WebSocket on a single port; it is easier behind a production proxy.
Practice Log the type of WebSocketServer
Import the WebSocketServer class from ws. Log typeof WebSocketServer.
Starter code
// import the module, get the server class
// log its typeSample solution
const { WebSocketServer } = require("ws");
console.log(typeof WebSocketServer);Expected output
function
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the option name
const wss = new WebSocketServer({ ____: 8080 })
const wss = new WebSocketServer({ port: 8080 })
Explanation: The port option sets the listening port.
2 What does new WebSocketServer({ port: 8080 }) do?
- Dosya okur
- Starts a server on port 8080 Correct answer
- Connects a database
- Speeds up the network
Explanation: It starts a WebSocket server on the given port.
3 Match each piece to its role
| Term | Meaning |
|---|---|
new WebSocketServer |
Creates a server |
wss.on("connection") |
On client connect |
ws.on("message") |
On message |
ws.send |
Sends a message |