成功回调socket.io中的emit方法

pra*_*ann 19 node.js socket.io

我试图从我的客户端发出自定义消息.我需要对其成功和失败采取一些行动.现在,我如何将成功回调附加到emit方法?

对于错误回调,我使用了Exposed events doc并使其正常工作

socket.on('error', () -> console.log("Error Occured"))
Run Code Online (Sandbox Code Playgroud)

为了成功,我试过了

socket.emit('my custom method', {content: json},() -> console.log("Emitted"))
Run Code Online (Sandbox Code Playgroud)

无论是成功还是失败,都不会触发此回调.

我怎样才能掌握成功处理程序?

小智 62

如果您查看文档,它会向您显示一个传递回调函数的示例 - 最后一个示例:http://socket.io/docs/#sending-and-getting-data-(acknowledgements )

防爆服务器:

    socket.on('formData', 
              function(data, fn){
                      // data is your form data from the client side
                      // we are here so we got it successfully so call client callback
                      // incidentally(not needed in this case) send back data value true 
                      fn(true);
              }
             );
Run Code Online (Sandbox Code Playgroud)

客户:

      socket.emit('formData', 
                  data, 
                  function(confirmation){
                          // send data
                          // know we got it once the server calls this callback      
                          // note -in this ex we dont need to send back any data 
                          // - could just have called fn() at server side
                          console.log(confirmation);
                  }
                 );
Run Code Online (Sandbox Code Playgroud)

  • +1请注意,这不适用于广播https://github.com/cayasso/primus-rooms/issues/28 (5认同)

tox*_*e20 15

你的第二个代码没有做任何事情的原因是因为socketIO中的暴露事件只是为socket.on方法定义的.因此,您需要在服务器app.js中添加另一个emit来完成此操作

客户端发出自定义消息并通过socket.emit将JSON数据发送到套接字,同时他还获得一个处理成功回调的更新函数

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

服务器端从客户获取来自消息emit的调用,并将messageSuccess发送回客户端

socket.on ('message', function (data) {
 io.sockets.emit ('messageSuccess', data);
});
Run Code Online (Sandbox Code Playgroud)

您可能可以使模块不受此行为的影响,因此您可以为希望以这种方式处理的每条消息附加此模块.

  • 这不应该是"正确的"答案,因为socket.io支持"确认函数",您可以在其中传递在"另一侧"调用的函数.请看其他的anser! (12认同)
  • 我有点困惑,哪种方式更好,从服务器发出`emit`事件或从客户端发送回调函数.`socket.emit('message',{hello:'world'},function(){// do stuff here});`这两种方法有什么区别吗? (3认同)