After multiple clients establish a connection to the server, the Socket.io () server has a sockets property value that is the socket object that establishes the connection to the client. You can use the Send method or the 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 Code code 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 Code code as follows:
<! DOCTYPE html>
<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 in .<br/>";
});
document.getElementById ("Result"). Innerhtml=str;
});
function Add () {
Socket.emit ("Login", document.getElementById ("nickname"). Value);
}
</script>
<body>
Nickname <input type= "text" id= "nickname"/>
<div id= "Result" ></div>
<input type= "button" onclick= "Add ()" value= "Login"/>
</body>
Run Result:
Google browser in the login, you can see the same results in Firefox.
This is a wonderful phenomenon, but also an effect that I am extremely surprised.
Such a wonderful node.