tezvyn:

Socket.IO emit methods: socket, io, broadcast differences?

AI-drafted, machine-checkedSource: interviewbeginner
WHAT IT TESTS

Socket.IO API design and message scope understanding.

OUTLINE

socket.emit() sends to one client, broadcast.emit() to all except sender, io.emit() to all.

SOCKET.EMIT FOR SINGLE CLIENT

socket.emit('eventName', data) sends a message to only that one client. This is unicast. Use this for server responses: Acknowledging a button click, confirming a login, sending private notifications to a specific user. Example: Server receives a user's profile update request, validates it, then socket.emit() a confirmation only to that user.

IO.EMIT FOR ALL CLIENTS

io.emit('eventName', data) broadcasts to every connected socket in the namespace. This is one-to-all. Use this for global state changes that affect everyone: A new user joined the system, a product went out of stock, a scheduled announcement. Example: Admin triggers a system maintenance alert, all 10000 connected users receive it simultaneously via io.emit().

BROADCAST.EMIT FOR EVERYONE EXCEPT SENDER

socket.broadcast.emit('eventName', data) sends to all sockets in the namespace except the one that triggered it. This is selective one-to-many. Use this for social notifications: User posts a comment, all other users in the thread see it, but the poster themselves already know they sent it. Example: In a multiplayer game, one player moves; broadcast.emit() tells all other players the new position, but not back to the mover.

CONCRETE SCENARIOS

A chat room has users Alice, Bob, Charlie. Alice types and sends a message. Use socket.emit() to send a confirmation to Alice immediately (local echo). Use broadcast.emit() to notify Bob and Charlie of the new message. If a server maintenance window opens, use io.emit() so all users globally see the warning, regardless of which chat they are in.

COMMON PITFALL

Developers sometimes use io.emit() for notifications that should only go to specific users, flooding the system. Or they forget broadcast.emit() exists and use socket.emit() in a loop for each recipient, which is less efficient. Understanding the three patterns prevents both errors.

Read the original → socket.io

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.