socket.io - 如何访问未处理的消息?

pe-*_*ean 5 socket.io engine.io

你怎么能检测到你在 socket.io 连接上收到了一条你没有处理程序的消息?

例子:

// client
socket.emit('test', 'message');

// server
io.on('connection', function (socket) {
  console.log('connection received...');

  // logs all messages
  socket.conn.on('message', function(data) {
    console.log('this gets every message.');
    console.log('how do I get just the ones without explicit handlers?');
  });

  socket.on('other' function(data) {
    console.log('expected message');
  });
}
Run Code Online (Sandbox Code Playgroud)

小智 -1

我没有找到像 socket.io 那样的方法,但是使用一个简单的 js 函数将消息转换为 json 它可以完成相同的工作。在这里你可以尝试这个:

function formatMessage(packetType, data) {
    var message = {'packetType': packetType, 'data': data}
    return JSON.stringify(message)
}
Run Code Online (Sandbox Code Playgroud)

和:

socket.on('message', function(packet){
   packet = JSON.parse(packet)

   switch (packet.packetType) {
      case 'init':
   ...
Run Code Online (Sandbox Code Playgroud)

socket.send(formatMessage('init', {message}));
Run Code Online (Sandbox Code Playgroud)