Home > Web Front-end > JS Tutorial > body text

Broadcast message of socket.io in node.js_node.js

WBOY
Release: 2016-05-16 16:26:54
Original
1487 people have browsed it

After multiple clients establish connections with the server, the socket.io() server has a sockets attribute, and the attribute value is all the socket objects that have established connections with the client. You can use the send method or emit method of the object to All clients broadcast messages.

io.sockets.send("user communicated);

io.socket.emit("login",names);

Case

server.js code:

Copy code The 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 monitoring 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 The code is as follows:







<script><br>          var socket=io.connect();<br> socket.on("login", function (names) {<br>           var str="";<br>              names.forEach(function(name){<br>                         str ="User" name "Logged in.<br/>";<br>             });<br>                document.getElementById("result").innerHTML=str;<br>         });<br>          function add(){<br> ​​​​​ socket.emit("login",document.getElementById("nickname").value);<br> }<br> </script>


Nickname




Run result:

When logging in in Google Chrome, you can see exactly the same results in Firefox.

This is a wonderful phenomenon and an effect that surprises me greatly.

Such a wonderful node.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template