CodeBlanks Logo Icon CodeBlanks

emit and on

Learn events with socket.emit and socket.on.

socket.emit and socket.on

socket.emit(event, data) sends an event to the client. socket.on(event, callback) listens to events from the client. These two methods are the cornerstone of Socket.io.

Example: socket.emit("hello", { name: "Ayşe" }); sends the hello event with { name: "Ayşe" } data to the client. socket.on("message", (data) => console.log(data)); listens to message events from the client. emit sends, on listens. Event names are free; client and server must use the same name. Data is sent as the second parameter; it can be an object, array or primitive.

Message exchange

A real chat flow looks like this: the client sends a message with socket.emit("chat", message); the server listens with socket.on("chat", ...). The server broadcasts the message to all clients with io.emit("chat", message).

Example: socket.on("chat", (message) => { io.emit("chat", message); });. Here io.emit sends to all clients; socket.emit sends to one. The difference matters: send private replies to one client, broadcasts to everyone. The event name (chat) must be the same on both sides; otherwise the message is not received.

Practice Define a chat handler

Use the io object below. Define a chat listener with io.on("connection", (socket) => { socket.on("chat", (mesaj) => { console.log("Got: " + mesaj); }); }). Print "emit/on ready" with console.log.

Starter code

index.js
const socketIo = require("socket.io");
const io = socketIo();

// Inside io.on, define a chat listener
// write here

// Print "emit/on ready"
// write here

Sample solution

index.js
const socketIo = require("socket.io");
const io = socketIo();
io.on("connection", (socket) => {
  socket.on("chat", (mesaj) => { console.log("Got: " + mesaj); });
});
console.log("emit/on ready");

Expected output

emit/on ready

Questions and answers

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

1 Match each method to its role

Term Meaning
socket.emit Sends to client
socket.on Listens from client
event name Communication channel
data Payload sent

2 Which one sends a message to a single client?

index.js
socket.emit("mesaj", veri)
  • io.send(veri)
  • socket.broadcast.emit("mesaj", veri)
  • socket.emit("mesaj", veri) Correct answer
  • io.emit("mesaj", veri)

Explanation: socket.emit sends to a single client.

3 Complete the socket.on call

Question
socket.on("chat", (____) => { console.log("Message"); });
Answer
socket.on("chat", (mesaj) => { console.log("Message"); });

Explanation: The callback takes the mesaj parameter.

All lessons in Advanced