Broadcast messages for Socket.io in Node.js _node.js

Source: Internet
Author: User
Tags emit

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.