[英]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: 我的基本程序流程如下:
get_new_number
. get_new_number
。 get_new_number
from unique socket. get_new_number
。 emits
new_number
emits
new_number
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.