我如何有io.sockets.on调用外部/全局函数

How do I have io.sockets.on call an external/global function?

本文关键字:外部 调用 全局 函数 on sockets io      更新时间:2023-09-26

在Node.js中,我有以下代码可以正常工作:

var io = require('socket.io').listen(8082);
io.sockets.on('connection', function (socket) {
  socket.on('message', function (msg) { console.log("message"); console.log(msg); socket.send('Your msg received [[' + msg + ']]');  });
  socket.on('disconnect', function () { console.log("disconnect"); });
});

…但我想做的是以某种方式调用一个函数"外部":

function fnParseMsg(msgArgInFunction)
{
    // do some stuff with the msg...
    console.log("message"); console.log(msgArgInFunction); socket.send('Your msg received [[' + msgArgInFunction + ']]');
};
var io = require('socket.io').listen(8082);
io.sockets.on('connection', function (socket) {
  socket.on('message', fnParseMsg(msg));
  socket.on('disconnect', function () { console.log("disconnect"); });
});

我想象我需要使用闭包;

要设置回调,你只需传递函数,而不是调用它,除非你调用的函数返回一个函数

socket.on('message', fnParseMsg);

由于您希望在需要传递的fnParseMsg函数中使用socket,因此可以通过两种方式执行

socket.on('message', function(msg){
   fnParseMsg(msg,socket);
});
或者使用bind
socket.on('message', fnParseMsg.bind(null,socket));

bind调用将在函数调用时将socket添加到参数列表中。您需要修改fnParseMsg声明,使其具有socket参数

//For the first snippet using the anonymous function
function fnParseMsg(msgArgInFunction,socket) {
//For the second snippet using bind
function fnParseMsg(socket,msgArgInFunction) {