javascript - socket.io 回调函数不起作用

标签 javascript angularjs node.js sockets callback

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

相关文章:

javascript - 如何在无序列表中缩进换行?

javascript - 如何使用 HTML5 重命名下载的文件?

javascript - node.js 中的相对路径问题

javascript - 如果测试有错误,Karma 不会失败

html - Angular : How to uncheck all checkboxes with a link?

javascript - Md-对话框弹出框( Angular Material )作为新 View 加载(Yeoman)

angularjs - Visual Studio 2013 AngularJS 智能感知支持

node.js - 文件更改时,Nodemon 不会在 docker 容器中重新加载

angularjs - yo angular-fullstack 在本地 linux 上安装失败

javascript - 如何从对象数组中获取值