Success Callback for emit method in socket.io

前端 未结 2 1381
[愿得一人]
[愿得一人] 2021-01-31 05:14

Im trying to emit a custom message from my client. I need to perform some actions on its success and failure. Now, how can i attach the success callback to emit method?

2条回答
  •  迷失自我
    2021-01-31 05:21

    The reason why your second code is not doing anything is because exposed events in socketIO are just defined for socket.on methods. Therefore you need to add another emit in your server app.js to accomplish this

    Client emits the custom message and sends JSON data to the socket via socket.emit, also he gets an update function that handles the success callback

    socket.emit ('message', {hello: 'world'});
    socket.on ('messageSuccess', function (data) {
     //do stuff here
    });
    

    Server-side Gets a call from the message emit from the client and emits the messageSuccess back to the client

    socket.on ('message', function (data) {
     io.sockets.emit ('messageSuccess', data);
    });
    

    You could probably make a module out of this behavior so you can attach this for every message that you want to be handled that way.

提交回复
热议问题