Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send response back to client using socket.io?

I have socket.emit call from client to server in response i want to have filename to the client that is not happening with below code not sure what is implemented wrong any idea, I do not see any error. How can i get response fro server using socket.emit ?

client.js

 socket.emit('startRecording',function (response) {
            console.log('start recording emit response',response);
        });

server.js

 socket.on('startRecording',function () {
        var response;
        logsRecording(function (filename) {
            response = filename;
            return response;
            //socket.emit('filename',filename);
        });
like image 653
hussain Avatar asked Jul 21 '16 14:07

hussain


1 Answers

To acknowledge the message, your handler for the startRecording event needs to accept an acknowledgement callback as a parameter. You can then call that with your desired data. See Sending and getting data (acknowledgements)

socket.on('startRecording',function (socket, ackFn) {
    var response;
    logsRecording(function (filename) {
        ackFn(filename);
    });
});

Alternatively, you could add a listener for that filename event you have commented out, in the client.js:

socket.emit('startRecording');
socket.on('filename', function(filename) {
    console.log('Filename received: ' + filename);
});

It might be helpful to run through Get Started: Chat application starting at the heading "Integrating Socket.IO" to get a more general understanding of Websockets.

like image 141
Will Avatar answered Sep 22 '22 08:09

Will