我曾经使用 socket.io 发出如下回调:
客户:
mysocket.emit('helloword', 'helloword', function(param){
console.log(param);
});
服务器:
var server = require('http').Server(app);
var sserver = io(server);
sserver.on('connection', function(socket){
console.log('connection');
socket.on('helloword', function(message, callback){
console.log(message);
console.log(callback+'');
console.log('arguments', arguments);
callback('helloword');
})
});
server.listen(config.port);
我正在使用angular-socket-io作为 socket.io-client 的包装器。我的服务很简单:
'use strict';
angular.module('core').factory('mysocket', function(socketFactory){
return socketFactory();
});
服务器输出:
connection
helloword
function (){
// prevent double callbacks
if (sent) return;
var args = Array.prototype.slice.call(arguments);
debug('sending ack %j', args);
var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
self.packet({
id: id,
type: type,
data: args
});
}
arguments { '0': 'helloword', '1': [Function] }
我的客户端控制台:
我的问题:
- 为什么我的回调没有触发?
最佳答案
函数socket.on(event,callback)
将监听来自客户端的事件,然后在事件触发时运行回调。在您的情况下,当它听到“helloword”时,它将运行您定义为第二个参数的回调函数:function(message,callback)
。您的服务器日志输出显示,实际上,回调中的所有 console.log
调用都正在运行。
关于javascript - socket.io 回调函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28618623/