CodeBlanks Logo Icon CodeBlanks

Connection

Learn to accept connections with ws.on('connection').

The connection event

When a client connects the "connection" event fires. You catch it with wss.on("connection", (ws, req) => { ... }). ws is the client connection, req is the HTTP request (handshake).

This event is ideal for sending a welcome message or authenticating the client. For example you greet the new user with ws.send("welcome"). You also register ws.on("message"), ws.on("close"), ws.on("error") here. Each client has its own ws object.

The ws object

For each connected client a ws object is created. This object is an EventEmitter; it emits message, close, error events.

You send messages to the client with ws.send(data). ws.readyState gives the connection state: 0 (connecting), 1 (open), 2 (closing), 3 (closed). You close the connection with ws.close(). Messages can be strings, Buffers, or objects; you send objects with ws.send(JSON.stringify(obj)).

Practice Register a connection handler

Create an EventEmitter (new EventEmitter()). Listen for the "connection" event with a handler. Then log "connection ready".

Starter code

index.js
// import EventEmitter, create one

// listen for the connection event

// log "connection ready"

Sample solution

index.js
const { EventEmitter } = require("events");
const wss = new EventEmitter();
wss.on("connection", (ws, req) => {});
console.log("connection ready");

Expected output

connection ready

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each piece to its role

Term Meaning
wss.on("connection") On client connect
ws Client connection
ws.send Sends a message
req HTTP request

2 Complete the event name

Question
wss.on("____", (ws, req) => { ws.send("hoş geldin"); })
Answer
wss.on("connection", (ws, req) => { ws.send("hoş geldin"); })

Explanation: The connection event fires when a client connects.

3 What parameters does the connection handler take?

  • (port, host)
  • (data, err)
  • (ws, req) Correct answer
  • (sql, values)

Explanation: The handler takes ws (client connection) and req (HTTP request).

All lessons in Advanced