Javascript io.emit 与 socket.emit

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32674391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:04:03  来源:igfitidea点击:

io.emit vs socket.emit

javascriptnode.jssocketssocket.io

提问by Manu

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.emitand io.emitbut I can't find an explanation anywhere.

我是 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);

That's my server stuff however when I change the ioto socketthat message only gets displayed when the user who is connecting connects. io.emitsends the message to all users.

这是我的但是服务器的东西时,我改变iosocket该消息时,用户是谁连接的连接将仅被显示。io.emit将消息发送给所有用户。

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.

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

回答by Kent Aguilar

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.

Hope this helps!.

希望这可以帮助!。

回答by keji

The iovariable represents the group of sockets. The code you have starts on line one with providing a function in the second parameter that gives you a socketvariable every time a new connection is made. The socketvariable is only for communicating with each individual connection. You may not see it in the code but there will be one socketvariable for each connection established

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

回答by Shama

That's a good question. Here is a sample code that might answer your question.

这是个好问题。这是一个示例代码,可以回答您的问题。

server.js code:

server.js 代码:

// Listener for incoming Socket connections

// 传入 Socket 连接的监听器

io.on('connection', function(socket){
  socket.on('send', function(msg){
    console.log('message received/sending: ' + msg);
    io.sockets.emit('new', msg);
  });
});

index.html code

index.html 代码

<body>
    <ul id="messages"></ul>
    <form action="">
        <input id="m" autocomplete="off" />
        <button type="submit">Send</button>
    </form>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
    <script>
        var socket = io();
        function send(msg) {
            console.log("emitting: " + msg);
            socket.emit('send', { "message": msg });
        }

        socket.on('new', function (msg) {
            console.log("msg " + msg.message);
            $('#messages').append($('<li>').text(msg.message));
        });

        $(function () {
            $('form').submit(function (e) {
                e.preventDefault();
                send($('#m').val());
                $('#m').val('');
                return false;
            });
        });
    </script>
</body>

In index.htmlsocket.emit('send', { "message": msg });this line of code actually sends/emits message to server which is waiting to listen on socket.on('send', function(msg){this line of code in server.js.

index.html 中,socket.emit('send', { "message": msg });这行代码实际上向正在等待侦听server.js 中的socket.on('send', function(msg){这行代码的服务器发送/发出消息。

Now io.sockets.emit('new', msg);this line from server.jsemits that message to all its sockets and is displayed to users using its listener in index.htmlthat is socket.on('new', function (msg) {.

现在,io.sockets.emit('new', msg);来自server.js 的这一行将该消息发送到其所有套接字,并使用其在index.html中的侦听器显示给用户socket.on('new', function (msg) {

Simply said Each socket emits its msg to a server(io is an instance of server) and server, in turn, emits it to all connected sockets. That is how msg sent by any user is displayed to all users. I hope it helps!

简单地说,每个套接字将其 msg 发送到服务器(io 是服务器的一个实例),而服务器又将其发送到所有连接的套接字。这就是任何用户发送的 msg 显示给所有用户的方式。我希望它有帮助!