15
votes

I am confused on what the 'socket' parameter is that is passed with the function (In 'The enigma' section). Then the parameter gets used 'socket.on'. What is the difference between io.on and socket.on?

The following code is slightly adapted from the Socket.io chat application example.

Variables

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

The enigma

io.on('connection', function (socket) {
  console.log('user connected');
  socket.on('message', function(msg) {
    console.log('message: ' + msg);
    io.emit('message', msg);
  })
});

Start server

server.listen(3000, function() {
  console.log('server is running');
});

index.jade

body
  script(src="/socket.io/socket.io.js")

form(method='post', action="/")
  input(type='text', id='user', autocomplete='off')
  input(type='submit', onClick="myFunc()")

strong messages:
  p(id="messages")

script.
  var socket = io();

  socket.on('message', function(msg) {
    console.log('client: ' + msg);
  });

  function myFunc() {
    var text = document.getElementById('user');
    socket.emit('message', text.value);
    text.value = '';
  };
1
a new socket gets created whenever a new user connects to the io (that is set up with your server), the socket listens on your user client side actions with socket.on method , (e.g messages), and then executes a callback function (e.g broadcast that message to all other connected users via io.emit(...). I think the io object is for the server to listen on global events (e.g new user connects) or for broadcasting from server to all other users... whereas the socket object is rather to react for user-specific events.. but I'm not a 100% sure of all the differences there... - ChillaBee

1 Answers

15
votes

In your code example, io is a Socket.IO server instance attached to an instance of http.Server listening for incoming events.

The socket argument of the connection event listener callback function is an object that represents an incoming socket connection from a client.

Both of them can listen for events with the on method.

It might help you visually understand how the two are separate if you re-imagine your code sample like this:

var connectionEvent = function(socket) {
    console.log('user connected');
    socket.on('message', function(msg) {
        console.log('message: ' + msg);
        io.emit('message', msg);
    });
};

io.on('connection', connectionEvent);