socket.io中的发射方法的成功callback

我试图从我的客户端发出自定义消息。 我需要对其成功和失败采取一些行动。 现在,我怎样才能附加成功callback发射方法?

对于错误callback,我使用暴露事件文档,并得到它的工作

socket.on('error', () -> console.log("Error Occured")) 

为了成功,我试了一下

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

不pipe这个callback是成功还是失败,这个callback都不会被触发。

我怎样才能获得成功处理程序?

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

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

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

服务器端从客户端发出的消息中获取一个调用,并将messageSuccess发送回客户端

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

您可能可以从此行为中创build一个模块,以便您可以将这个附加到您想要以这种方式处理的每条消息。

如果你看看这个文档,它会向你展示一个传递callback函数的例子 – 第二个例子: http ://socket.io/docs/#sending-and-getting-data-(acknowledgements )

Ex服务器:

  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); } ); 

客户:

  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); } );