Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.on('connection' ... event never fired nodejs + express + socket.io

Problem socket.io NOT working

Details

  • Generated a project with express [folder]; cd [folder]; npm install;
  • Setup socket.io npm install socket.io
  • Run node app with below code
  • Client connect event fires but server connection NEVER fired.

Setup

  • Server AWS Free Tier, Ubuntu 11.10, ami-a7f539ce
  • nodejs v0.6.5
  • express v2.5.1
  • socket.io v0.8.7

Client

 var socket = io.connect('http://example.com:3000');

 socket.on('connect', function() { 
    console.log('connected');
 });

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

 socket.on('disconnect', function() {
    console.log('disconnected');
 });

 socket.on('error', function (e) {
    console.log('System', e ? e : 'A unknown error occurred');
 });

Server

 [...]

 app.listen(3000);

 // socket.io setup
 var socket = require('socket.io').listen(app);

 // socket.io connection establishment
 socket.on('connection', function (client) {
    client.send("hello");
    console.log("hello", client);           
 });

Why is connection event never fired?

like image 320
Gaston Morixe Avatar asked Dec 08 '11 01:12

Gaston Morixe


Video Answer


1 Answers

Took a while to notice... the connection event is emmited on io.sockets. In your code this would be

socket.sockets.on('connection', function (client) {
  client.send("hello")
  console.log("hello", client)
})

You should use io instead of socket as the var name to avoid this confusion.

like image 83
Ricardo Tomasi Avatar answered Nov 15 '22 21:11

Ricardo Tomasi