0

In the official site of socket.io i have a code example, my doubt is, the emit function will emit the event for all client or just for the client who connected in the sever? The example code:

Server (app.js):

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(80);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

Client (index.html):

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>
  • 1
    It's done per connection. Each connection to server essentially creates a socket object passed into the callback. – raina77ow May 05 '17 at 16:04
  • You can refer this answer for all different responses, [Check out](http://stackoverflow.com/questions/10058226/send-response-to-all-clients-except-sender-socket-io#answer-10099325) – Mehul Prajapati May 06 '17 at 07:44

1 Answers1

3

the emit function will emit the event for all client or just for the client who connected in the sever?

In your code example on the server:

socket.emit(...) will send a message only to that particular connection.

io.emit(...) will send a message to all currently connected clients.

Keep in mind that io.emit() doesn't have any magical powers, it just loops through all the current connected clients and calls socket.emit() for each one individually using their particular socket object - saving you the work of having to write that code yourself.

From the client, socket.emit() will send a message to the server.

jfriend00
  • 683,504
  • 96
  • 985
  • 979