【问题标题】:socket.io callback function not workingsocket.io 回调函数不起作用
【发布时间】:2015-02-19 22:56:22
【问题描述】:

我曾经使用 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] }

我的客户端控制台:

我的问题:

  • 为什么我的回调没有触发?

【问题讨论】:

    标签: javascript angularjs node.js sockets callback


    【解决方案1】:

    函数socket.on(event, callback) 将监听来自客户端的事件,然后在事件触发时运行回调。在您的情况下,当它听到“helloword”时,它将运行您定义为第二个参数的回调函数:function(message, callback)。您的服务器日志输出显示,实际上,您的回调中的所有 console.log 调用都在运行。

    【讨论】:

    • 我不是在谈论在服务器中运行的回调。是关于从服务器触发的客户端上运行的回调
    • 我的客户端中的 console.log 没有触发
    【解决方案2】:

    要查看客户端发生了什么,请尝试设置 localStorage.debug = '*' 有关更多信息,请参阅此内容:http://socket.io/docs/migrating-from-0-9/#log-differences(假设您使用的是 socketio 1.0+)

    【讨论】:

      猜你喜欢
      • 2014-10-24
      • 2014-10-24
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多