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: