io.emit vs socket.emit [英] io.emit vs socket.emit

查看:267
本文介绍了io.emit vs socket.emit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是socket.io的新手并且遇到了一些看似很奇怪的东西。我实际上并不知道 socket.emit io.emit 之间的区别,但我找不到解释任何地方。

I'm new to socket.io and have run in to something that seems pretty weird. I don't actually know the difference between socket.emit and io.emit but I can't find an explanation anywhere.

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 将消息发送给所有用户。

That's my server stuff however when I change the io to socket that message only gets displayed when the user who is connecting connects. io.emit sends the message to all users.

也许它应该是那样的,或者只是它的一些可怕的黑客?如果您需要客户端HTML,请告诉我。

Maybe it's supposed to be like that or maybe its just some horrible hack? Let me know if you need the client side HTML.

推荐答案

这是一个补充文档供参考。

Here's a supplementary documentation for reference.

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.

希望这会有所帮助!

这篇关于io.emit vs socket.emit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆