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

Source: Internet
Author: User
This article mainly introduces node. socket. io broadcast messages. For more information, see socket. 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:

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 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 is as follows:







Related Article

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.