Man*_*anu 41 javascript sockets node.js socket.io
我是socket.io的新手并且已经遇到了一些看似很奇怪的东西.我实际上并不知道和之间的区别socket.emit,io.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);
Run Code Online (Sandbox Code Playgroud)
这是我的服务器的东西,但当我更改io到socket该消息时,仅在连接的用户连接时显示.io.emit将消息发送给所有用户.
也许它应该是那样的,或者它只是一些可怕的黑客?如果您需要客户端HTML,请告诉我.
Ken*_*lar 75
这是一份补充文件供参考.
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.
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!.
kej*_*eji 31
该io变量表示套接字组.您所拥有的代码从第一行开始,在第二个参数中提供一个函数,socket每次建立新连接时都会为您提供一个变量.该socket变量仅用于与每个单独的连接进行通信.您可能无法在代码中看到它,但socket每个建立的连接都会有一个变量
socket.emit 只会向发件人发回消息,io.emit 将消息发送给包括发件人在内的所有客户端socket.broadcast.emit| 归档时间: |
|
| 查看次数: |
17721 次 |
| 最近记录: |