首页 > 解决方案 > Receive socket.io messages outside of connection

问题描述

I know that messages can be sent outside the socket connection code block. How can I receive messages from the client the same way?

// Create socket.io server attached to current HTTP server
var io = require('socket.io')(server);

// When connection is made, set up some definitions for the server's connections
io.on('connection', (socket) => {
  console.log('Local server connected...');
  socket.on('disconnect', () => {
    console.log('Local server disconnected...');
  });
  
  // I can receive messages here
  socket.on('sendToRemote', function (data) {
    console.log(data);
  });

});

// Messages can be received outside the socket code using this syntax:
io.of('/').emit('runCamera', "Client connected...");

// I can't receive messages here...
// How can the server receive messages outside the socket code?
// I tried using the code below but it didn't work.
// Syntax compiles but doesn't work like the one above.
io.of('/').on('sendToRemote', function (data) {
  console.log(data);
});

标签: node.jsexpresssocketssocket.io

解决方案


您需要有一个套接字来从中获取消息。你可以发射到一个房间,因为它正在跟踪连接到那个房间的所有插座。因此,要仅在特定房间中获取消息:

io.of('/').on('connection', function (socket) {
  socket.on("sendToRemote", function (data) {
    console.log(data);
  });
});

推荐阅读