首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >io.emit vs socket.emit

io.emit vs socket.emit
EN

Stack Overflow用户
提问于 2015-09-20 08:01:47
回答 2查看 33.5K关注 0票数 62

我是socket.io的新手,遇到过一些看起来很奇怪的事情。我实际上不知道socket.emitio.emit之间的区别,但我在任何地方都找不到解释。

代码语言:javascript
复制
io.on('connection', function(socket){
  io.emit('connected')  // <<<< HERE >> socket.emit('connected');
  socket.on('disconnect', function(){
    io.emit('disconnect')
  });
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

server.listen(3000);

这是我的服务器设置,但是,当我将io更改为socket时,该消息仅在连接的用户连接时显示。io.emit将消息发送给所有用户。

也许它应该是这样的,或者它只是一些可怕的黑客?让我知道,如果你需要客户端的HTML。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-11-27 22:17:48

这里有一个补充文档供参考。

代码语言:javascript
复制
socket.emit('message', "this is a test"); //sending to sender-client only
socket.broadcast.emit('message', "this is a test"); //sending to all clients except sender
socket.broadcast.to('game').emit('message', 'nice game'); //sending to all clients in 'game' room(channel) except sender
socket.to('game').emit('message', 'enjoy the game'); //sending to sender client, only if they are in 'game' room(channel)
socket.broadcast.to(socketid).emit('message', 'for your eyes only'); //sending to individual socketid
io.emit('message', "this is a test"); //sending to all clients, include sender
io.in('game').emit('message', 'cool game'); //sending to all clients in 'game' room(channel), include sender
io.of('myNamespace').emit('message', 'gg'); //sending to all clients in namespace 'myNamespace', include sender
socket.emit(); //send to all connected clients
socket.broadcast.emit(); //send to all connected clients except the one that sent the message
socket.on(); //event listener, can be called on client to execute on server
io.sockets.socket(); //for emiting to specific clients
io.sockets.emit(); //send to all connected clients (same as socket.emit)
io.sockets.on() ; //initial connection from a client.

希望这能有所帮助!

票数 160
EN

Stack Overflow用户

发布于 2015-09-20 11:29:55

io变量表示套接字组。您的代码从第一行开始,在第二个参数中提供了一个函数,该函数在每次建立新连接时为您提供一个socket变量。socket变量仅用于与每个单独的连接进行通信。您可能在代码中看不到它,但是每个建立的连接都有一个socket变量

票数 37
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32674391

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档