Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Socket.io node.js Socket.emit不工作_Node.js_Socket.io - Fatal编程技术网

Socket.io node.js Socket.emit不工作

Socket.io node.js Socket.emit不工作,node.js,socket.io,Node.js,Socket.io,我基本上有一个Node.js服务器,它充当其他两台服务器之间的中间人 我想知道是否可以这样做: let matchSocket = ioClient.connect('http://localhost:5040'); http.listen(5030, function () { console.log('Matchmaking server is now running.'); }); matchSocket.on('connect', function () { }); io.o

我基本上有一个Node.js服务器,它充当其他两台服务器之间的中间人

我想知道是否可以这样做:

let matchSocket = ioClient.connect('http://localhost:5040');

http.listen(5030, function () {
  console.log('Matchmaking server is now running.');
});

matchSocket.on('connect', function () {

});

io.on('connection', function (socket) {
  // Send event 'ev001' as a CLIENT
  socket.on('ev001', function (data, callback) {
      matchSocket.emit('start', {
            message: 'message'
          });
   }
}
这个“服务器”既是服务器又是客户机。鉴于此服务器收到消息“ev001”,我想将另一条消息转发到另一台服务器

所以它变成了这样:

服务器A->ev001->此服务器(B)->启动->服务器C

你能在套接字自己的“socket#on()”函数之外调用socket#emit()函数吗?

是的,这是可能的

这是一个独立版本(它创建了一个在5040上侦听的服务器,很像您连接的远程服务器,也创建了一个在5030上侦听的服务器,很像您的“配对服务器”):

const ioServer = require('socket.io');
const ioClient = require('socket.io-client');

// Your remote server.
ioServer().listen(5040).on('connection', function(socket) {
  socket.on('start', function(message) {
    console.log('remote server received `start`', message);
  });
});

// Connect to the "remote" server.
let matchSocket = ioClient('http://localhost:5040');

// Local server.
ioServer().listen(5030).on('connection', function(socket) {

  // Send a message to the remote server when `ev001` is received.
  socket.on('ev001', function(message) {
    console.log('received `ev001`');
    matchSocket.emit('start', { message: 'message' });
  });
});

// Connect to the local server and emit the `ev001` message.
ioClient('http://localhost:5030').emit('ev001');