Scott
Scott

Reputation: 481

Difference between io.on and socket.on in Socket.io?

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 = '';
  };

Upvotes: 17

Views: 18844

Answers (1)

Connor
Connor

Reputation: 1855

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);

Upvotes: 18

Related Questions