简体   繁体   English

我应该将服务器端侦听器放在io还是socket.io的套接字上?

[英]Should I put server-side listeners on io or socket for socket.io?

If I have my express.js server set up as such: 如果我这样设置express.js服务器:

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 8080;

server.listen(8080);

And elsewhere I have a io.on('connnect', function(socket){...}); 在其他地方,我有一个io.on('connnect', function(socket){...}); , should I be putting emit/event listeners on that socket within the io.connect(...) callback, or on the io object? ,我应该在io.connect(...)回调中的那个套接字上还是在io对象上放置发射/事件侦听器?

My basic program flow is as follows: 我的基本程序流程如下:

  1. Client socket emits get_new_number . 客户端套接字发出get_new_number
  2. Server receives get_new_number from unique socket. 服务器从唯一套接字接收get_new_number
  3. Based on that unique socket ID, it emits new_number 根据该唯一的套接字ID,它emits new_number
  4. The client listens for new_number and logs the data within to the console when triggered. 客户端侦听new_number并在触发时将数据记录到控制台中。

On the server-side, for part 2, I believe that must be a within the io.on('connect'...) function, so I can access socket.id for use later : 在服务器端,对于第2部分,我认为它必须在io.on('connect'...)函数中,因此我可以访问socket.id以供以后使用:

io.on('connect', function(socket){
    socket.on('get_new_number', function(){
        console.log('server got request for new number.');
        globalVarId = socket.id;        
    });
});

But from there, where should I emit a new number to that unique socket? 但是从那里,我应该在哪里向该唯一的套接字发出一个新的数字? Say I save the socket.id and then emit to only it, how can I do that? 假设我保存了socket.id ,然后仅将其发出,该怎么办? The below isn't working: 以下内容不起作用:

io.on('connect', function(socket){
    //get_new_number stuff
    socket.to(globalVarId).emit('new_number', {number: someNumber});
});

Should I instead later do a io.to(globalVarId).emit... ? 我是否应该稍后再执行io.to(globalVarId).emit...吗?

EDIT: For that matter, is there a way to put event listeners on the io object, such like 编辑:为此,有没有办法将事件侦听器放在io对象上,例如

io.on('someEvent', function(socket){
    console.log('this socket did a thing, ', socket.id);
});

You can assume that socket within the callback function represents a unique client/connection. 您可以假定回调函数中的socket代表唯一的客户端/连接。

So when you want to communicate with that client, you can use socket.emit() : 因此,当您想与该客户端通信时,可以使用socket.emit()

io.on('connect', function(socket) {
  socket.on('get_new_number', function() {
    console.log('server got request for new number.');
    //get_new_number stuff
    socket.emit('new_number', { number: someNumber });
  });
});

.to(...).emit(...) is used for something else entirely (sending a message to a particular room ). .to(...).emit(...)完全用于其他用途(向特定房间发送消息)。

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

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