Broadcast messages of socket. io in node. js, node. jssocket. io
After multiple clients establish a connection with the server. the io () server has a sockets attribute. The attribute value is all socket objects connected to the client. you can use the send method or emit method of this object to broadcast messages to all clients.
Io. sockets. send ("user commected );
Io. socket. emit ("login", names );
Case
Server. js code:
Copy codeThe Code is as follows:
Var express = require ("express ");
Var http = require ("http ");
Var sio = require ("socket. io ");
Var app = express ();
Var server = http. createServer (app );
App. get ("/", function (req, res ){
Res. sendfile (_ dirname + "/index.html ");
});
Server. listen (1337, "127.0.0.1", function (){
Console. log ("Start listening 1337 ");
});
Var io = sio. listen (server );
Var names = [];
Io. sockets. on ("connection", function (socket ){
Socket. emit ("login", names );
Socket. on ("login", function (name ){
Names. push (name );
Io. sockets. emit ("login", names );
});
});
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head lang = "en">
<Meta charset = "UTF-8">
<Title> </title>
<Script src = "/socket. io/socket. io. js"> </script>
<Script>
Var socket = io. connect ();
Socket. on ("login", function (names ){
Var str = "";
Names. forEach (function (name ){
Str + = "user" + name + "logged on. <br/> ";
});
Document. getElementById ("result"). innerHTML = str;
});
Function add (){
Socket. emit ("login", document. getElementById ("nickname"). value );
}
</Script>
</Head>
<Body>
Nickname <input type = "text" id = "nickname"/>
<Div id = "result"> </div>
<Input type = "button" onclick = "add ()" value = "login"/>
</Body>
</Html>
Running result:
Log on to Google's browser and you can see exactly the same results in Firefox.
This is a wonderful phenomenon and an effect that surprised me a lot.
Such a wonderful node.