Friday, 5 May 2017

How the emit function of socket io works?

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>



via Pedro Henrique Silva

No comments:

Post a Comment