Search code examples
node.jshttpwebsocketsocket.iorequest-response

How to do request-response pattern with WebSockets


I am using Socket.io, and I am wondering if there is a good way to use the request / response pattern. Is the best way to do this to use a UUID for each request, and then only handle data from a response that contains that UUID? That's perhaps not the most scalable way to do things.


Solution

  • Socket.io has the option to send an acknowledgement back. It's possible to include data into this callback (see here). I use it as follows:

    Server side:

    socket.on('event', function(msg, callback) {
     console.log('event received: '+msg);
     callback("Here could be your data");
    });
    

    Client side:

    socket.emit('event', "my data", function(callbackData){
        console.log('Callback data:', callbackData);
    });