简体   繁体   English

socket.io - 无法从服务器向特定客户端发送数据

[英]socket.io - can't emit data from server to specific client

So I'm trying to emit data from server to one specific client upon connecting (this is server code):所以我试图在连接时从服务器向一个特定的客户端发送数据(这是服务器代码):

io.sockets.on('connection', function(socket){
   socket.id = Math.random();

   //this works, but sends data to all clients, which is not what I need
   socket.emit('serverMsg');

   //this seems to do nothing
   io.to(socket.id).emit('serverMsg');

   //this also does nothing
   socket.broadcast.to(socket.id).emit('serverMsg');
});

As I've commented the lines, I can emit data to all clients, but nothing happens when I try to emit to specific client with socket.id.正如我对这些行的评论,我可以向所有客户端发送数据,但是当我尝试使用 socket.id 向特定客户端发送数据时没有任何反应。 What am I doing wrong?我究竟做错了什么? There are no error messages or anything.没有错误消息或任何东西。

When a client connects, its socket.id is automatically initialized.当客户端连接时,它的socket.id会自动初始化。 Also, it joins a room with the same name:此外,它加入了一个同名的房间

Each Socket in Socket.IO is identified by a random, unguessable, unique identifier Socket#id. Socket.IO 中的每个 Socket 都由一个随机的、不可猜测的、唯一的标识符 Socket#id 标识。 For your convenience, each socket automatically joins a room identified by this id.为方便起见,每个套接字都会自动加入由该 ID 标识的房间。

If, for some reason, you wish to redefine the id, you would need to assign the socket to the corresponding room as well, since the to( ) method expects as its argument the name of the room of interest.如果出于某种原因,您希望重新定义 id,您还需要将套接字分配给相应的房间,因为to( )方法需要将感兴趣的房间的名称作为其参数。 In the code in your post, you redefine the id , but the association with the corresponding room is not established, thus the emit method emits the data into the "void" (into a room the name of which is equal to the result of Math.random() , but which contains no sockets)...在你帖子的代码中,你重新定义了id ,但没有建立与相应房间的关联,因此emit方法将数据发送到“void”中(进入名称等于Math.random()结果的房间) Math.random() ,但不包含套接字)...

const customId = ....
socket.id = customId;

socket.join(customId);

io.to(customId).emit(...)

this work for me这对我有用

const http = require('http').createServer();
const sio = require('socket.io')(http);

var port = xxxx;
var ip = "xxx.xxx.x.x";

sio.on('connection', async function(socket) {
     sio.sockets.to(socket.id).emit("from_server", "your are connected"); 
});



http.listen(port, ip, function() {
    console.log('Server active. listening on :' + ip + ":" + port);
});

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

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