繁体   English   中英

Socket.io node.js socket.emit无法正常工作

[英]Socket.io node.js socket.emit not working

我基本上有一个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');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM