简体   繁体   中英

Socket.io node.js socket.emit not working

I basically have a Node.js server, which acts as a middleman between two other servers.

I am wondering if its possible to do something like this:

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'
          });
   }
}

This "server" is both a server and a client. Given that this server receives a message 'ev001', I want to forward another message onwards to another server.

So it becomes something like:

Server A -> ev001 -> This server (B) -> start -> Server C

Can you call a socket#emit() function outside of that socket's own "socket#on()" function?

Yes, that's possible.

Here's a standalone version (which creates a server listening on 5040, much like the remote server that you're connecting to, and also a server on 5030, much like your "Matchmaking server" ):

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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