Antonio Laguna
Antonio Laguna

Reputation: 9290

Can't emit by socket.io?

I recently updated socket.io to latest version which is 0.9.8

Last time I worked with the app, I did something like this:

io.sockets.emit("logged",this);

And it worked. Now I get:

TypeError: Cannot call method 'emit' of undefined
    at new Agent (/var/www/panel/models/agent.js:29:16)
    at module.exports (/var/www/panel/modules/app.js:35:47)
    at Query.Client.query (/var/www/panel/node_modules/mysql/lib/client.js:108:11)
    at Query.EventEmitter.emit (events.js:85:17)
    at Query._handlePacket (/var/www/panel/node_modules/mysql/lib/query.js:51:14)
    at Client._handlePacket (/var/www/panel/node_modules/mysql/lib/client.js:319:14)
    at Parser.EventEmitter.emit (events.js:88:17)
    at Parser.write.emitPacket (/var/www/panel/node_modules/mysql/lib/parser.js:71:14)
    at Parser.write (/var/www/panel/node_modules/mysql/lib/parser.js:576:7)
    at Socket.EventEmitter.emit (events.js:88:17)

I thought it was because something about scope or whatever so I just did this:

// server.js
var express = require('express'),
    server = express(),
    Routes = require('./routes'),
    App = require('./modules/app.js'),
    database = require('./libraries/mysql.js'),
    io = require('socket.io'),
    mysql = require('mysql');


server.listen(8080);
io.listen(server);
io.sockets.emit('Hi there', {});

And it just doesn't work, same error, different line.

What am I doing wrong?

Upvotes: 1

Views: 2458

Answers (1)

Linus Thiel
Linus Thiel

Reputation: 39261

You need to save the return value of socketio.listen and interact with that. I recommend you follow the examples at socket.io. Something like this should do the trick:

var express = require('express'),
    server = express(),
    socketio = require('socket.io');

server.listen(8080);
var io = socketio.listen(server);
io.sockets.emit('Hi there', {});

Or even:

var express = require('express'),
    server = express(),
    io = require('socket.io').listen(server);

server.listen(8080);
io.sockets.emit('Hi there', {});

Upvotes: 4

Related Questions