Acknowledgements and Input Validation

Return success or rejection from the server and set a timeout when waiting for an acknowledgement.

🎯 Introduction

If a user sends an empty message, the server should reject it and explain why. The client also needs to stop waiting if the server does not reply. This article associates a processing result with each submission, distinguishing success, application-level rejection, and an acknowledgement timeout.


🧱 What Is an Acknowledgement Callback?

Socket.IO lets the sender pass a function as the final argument to emit. The receiver calls the corresponding acknowledgement function after processing to return a result for that specific request. This mechanism is called an acknowledgement, often shortened to ack.

Here, success returns { ok: true } and rejection returns { ok: false, error: 'Reason' }. The application defines these fields; Socket.IO transports them.


🛠 Validate on the Server Before Acknowledging

Replace the existing chat:send listener in server.mjs with the following code. After trimming whitespace, each message must contain text and be no longer than 100 JavaScript string length units.

socket.on('chat:send', (text, reply) => {
    if (typeof reply !== 'function') {
        return;
    }
    if (typeof text !== 'string' || !text.trim() || text.trim().length > 100) {
        reply({ ok: false, error: 'Enter 1–100 characters' });
        return;
    }
    socket.emit('chat:message', text.trim());
    reply({ ok: true });
});

reply is our name for the acknowledgement function. Checking its type prevents an exception if an older client omits the callback. Return immediately after rejecting invalid input to avoid sending the message or acknowledging it twice.

The server must validate the data it actually receives even if the client restricts input, because client code can be modified. Some emoji have a length greater than 1. Use ordinary letters or Chinese characters for this exercise initially.

Wait No More Than Three Seconds on the Client

Replace the original emit call in the connect callback in client.mjs with the following code.

socket.timeout(3000).emit('chat:send', 'Hello', (error, result) => {
    if (error) {
        console.log('Acknowledgement timed out; the processing result is still unknown');
        return;
    }
    console.log(result.ok ? 'Accepted by server' : `Rejected by server: ${result.error}`);
});

timeout(3000) sets the acknowledgement waiting limit in milliseconds. With a timeout enabled, the first callback argument is the waiting error and the second is the server's data. A response with ok: false is still an acknowledgement, so it does not enter the timeout branch. Acknowledgements and timeouts


🧰 Compare the Three Outcomes

Restart both processes and first test success with “Hello”. Then change the message argument to three spaces and restart the client to test rejection.

ActionMessage returnedAcknowledgement
Send “Hello”Receive HelloAccepted by server
Send spacesNo messageRejected by server, with a reason
Temporarily remove reply from the success branch, then sendMessage still arrivesTimes out after about three seconds

For the third test, comment out only reply({ ok: true }), keeping socket.emit. This demonstrates that the server may process a message without the caller receiving an acknowledgement. Restore the code and restart the server afterward.


❓ Questions and Answers

Q1: Does a successful acknowledgement mean other users have read the message?

In this example, success only means the server validated the input and sent the message back. Read receipts require the receiving user to report that the message has been read separately.

Q2: What happens if I resend immediately after a timeout?

You may create duplicates because the earlier operation might already have completed. Reliable retries require a stable request ID for the same submission and a server-side check for previous processing. The message recovery article distinguishes missing messages from duplicates.


🧪 Exercise

Add a server-side rule rejecting messages made up entirely of digits. Sending “123” should be rejected, while “Order123” should succeed. Return a clear reason for invalid input and call the acknowledgement function only once per submission.


🎉 Each submission now has a verifiable processing result and a limit on how long to wait.