gpt4 book ai didi

javascript - io.emit 与 socket.emit

转载 作者:IT老高 更新时间:2023-10-28 21:56:35 27 4
gpt4 key购买 nike

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

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,请告诉我。

最佳答案

这是一个补充文档供引用:

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.

希望这会有所帮助!

编辑:socket.io 文档也包含类似的 cheatsheet .

关于javascript - io.emit 与 socket.emit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32674391/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com