Broadcast messages of socket. io in node. js, node. jssocket. io

Source: Internet
Author: User

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.

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.