Emitting and Listening for Events
🎯 Introduction
Previously, only the server sent a welcome message. Now the client will send “Hello” and the server will reply “Received”. This lets you send application data to the backend and return the processing result.
🧱 Event Names and Data
Use emit to send events and on to receive them. In socket.emit('chat:send', 'Hello'), chat:send is the event name and Hello is the data. The other side must register socket.on('chat:send', ...) beforehand to run its handler when the event arrives.
Registering a listener means “call this function whenever this happens”; calling on does not immediately process a message. Event names must match: chat:send and chat:Send are different names. The colon is simply a naming convention, meaning “the send action in the chat feature”.
🛠 Send a Message and Receive a Reply
Add this code below the welcome message in the existing connection callback in server.mjs.
socket.on('chat:send', (text) => {
console.log('Message received', text);
socket.emit('chat:message', `Received: ${text}`);
});
When called on the server, socket.emit targets the client associated with that socket. Each client currently receives only its own reply. The next section of the course introduces delivery between multiple users.
Replace client.mjs with the following code. It sends “Hello” immediately after connecting.
import { io } from 'socket.io-client';
const socket = io('http://localhost:3000');
socket.on('connect', () => {
console.log('Connected');
socket.emit('chat:send', 'Hello');
});
socket.on('chat:message', (text) => {
console.log('Received', text);
});
socket.on('connect_error', (error) => {
console.log('Connection failed', error.message);
});
io() starts connecting automatically. Once connected, Socket.IO triggers the client's connect event, and our callback calls emit. The server receives chat:send and returns chat:message; the matching client listener prints the result.
Press Ctrl+C to stop the previous server and client, then run node server.mjs and node client.mjs in their respective terminals. The client sends automatically at startup. Expect the following output.
Server terminal
Server started: http://localhost:3000Client connected <connection ID>Message received Hello
Client terminal
ConnectedReceived Received: Hello
<connection ID> is generated at runtime. Change the second argument of emit to “Test message” and restart the client to see the text change accordingly.
🧰 What Data Can You Send?
A string works for a single piece of text. To send message text and a nickname together, use a plain object.
socket.emit('chat:send', { text: 'Hello', nickname: 'User A' });
The server listener's first argument is now an object; read its text with message.text. Both sides must agree on the data format. The next article continues using strings, so you do not need to change the project yet.
Socket.IO directly supports plain objects, arrays, and binary data. You do not need to call JSON.stringify on plain objects. Functions generally cannot be sent as ordinary application data; the next article explains the special role of a callback passed as the last argument. Emitting events
Persistent Listeners, One-Time Listeners, and Removing Listeners
on runs each time an event with that name arrives. To print a notice only for the first message, use once, which removes itself after running once.
socket.once('chat:message', () => {
console.log('First message round trip complete');
});
To stop handling an event, remove its listener with off.
function handleMessage(text) {
console.log(text);
}
socket.on('chat:message', handleMessage);
socket.off('chat:message', handleMessage);
Pass off the same function used during registration. Here, the listener is removed immediately, so subsequent messages will not reach handleMessage. The connection itself stays open. Listening to events
❓ Questions and Answers
Q1: Why is one message printed twice?
Check whether two listeners that print output were registered for the same event. Each call to on adds a function. This course registers application listeners during client initialization, and once per new connection on the server.
Q2: Does emitting an event mean the server processed it successfully?
You still need matching event names, data the server can process, and application logic that completes without errors. The next article makes the server explicitly report success or rejection.
🧪 Exercise
Add a one-time listener on the client. In the connect callback, call emit three times to send “First”, “Second”, and “Third”. There should be three regular replies and only one “First message round trip complete” notice. Temporarily change the emitted event name to an incorrect name and confirm that the server does not log the corresponding message, then restore the name.
🎉 You can now follow event names to locate message emission, backend processing, and result handling.
