After multiple clients establish connections with the server, the socket.io() server has a sockets attribute, and the attribute value is all socket objects that establish connections with the client. You can use the send method or emit method of the object to broadcast messages to all clients.
io.sockets.send("user edited);
io.socket.emit("login",names);
Case
Server.js code:
The code copy 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);
});
});
The code copy 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+"Login.<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 results:
Log in to Google Chrome and you can see the same results in Firefox.
This is a wonderful phenomenon and an effect that surprised me very much.
Such a wonderful node.