Socket.io 'on' is returning undefined - node.js

Ok, so I'm trying to learn socket.io and I get this error:
io.socket.on('connection', function (socket)
TypeError: Cannot call method 'on' of undefined
heres my code:
var express = require('express')
, app = express.createServer()
, routes = require('./routes')
, user = require('./routes/user')
, path = require('path')
, io = require('socket.io').listen(app);
// all environments
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000);
app.get('/', routes.index);
app.get('/users', user.list);
io.socket.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
I know its going to be something rather obvious.

Should be io.sockets.on ("sockets" instead of "socket"):
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});

I think that this code is no longer working.
Here is something I made to deal with socket.io and a http server.
var app = require('http'),
io = require('socket.io');
var handler = function(req, res) { /* your handler function*/ };
var server = app.createServer(handler).listen( 8000 );
var ios = io.listen(server);
ios.sockets.on('connection', function(socket){
socket.emit('message', {'message': 'hello world'});
});

Related

Socket.IO with Express.JS routing

Creating my small chat wasn't too hard, but now I am trying to create real-time comments system. My current configuration uses latest Node, Express and Socket.IO and I have no idea how to create separate comment page. How to connect Express' routing and SocketIO when routes are defined before I can open socket connection?
var express = require('express');
var app = express();
var swig = require('swig');
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.set('view cache', false);
app.use(express.static(__dirname + '/public'));
swig.setDefaults({ cache: false });
app.get('/', function (req, res) {
res.render('chat');
});
var server = app.listen(80);
var io = require('socket.io').listen(server);
io.on('connection', function (socket) {
socket.emit('open', messages);
socket.on('message', function (data) {
socket.broadcast.emit('message', data);
});
});

Express Socket.io example server not working

I'm trying to learn socket.io and their example for Express isnt working. Heres my code:
app.js:
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, server = require('http').createServer(app)
, path = require('path')
, io = require('socket.io').listen(app);
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('less-middleware')({ src: __dirname + '/public' }));
app.use(express.static(path.join(__dirname, 'public')));
server.listen(3000);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.jade');
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
and my index.jade file:
extends layout
block content
script(src="/node_modules/socket.io/lib/socket.io.js")
script(
var socket = io.connect('http://localhost:3000');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
)
When I go to my localhost the browser just keeps waiting on a response. It eventually times out.
Most of the other questions related to this question had some odd implementation of the example code. I'm literally just trying to implement it as they show.
The problem is you are creating app after you are creating io. So this line
, io = require('socket.io').listen(app);
is effectively the same as
, io = require('socket.io').listen(undefined);
remove this line
var app = express();
And somewhere between the first line and io = require('socket.io') add , app = express()

Socket.io and Express3 - 404 on client request to /socket.io/socket.io.js

I am receiving a 404 when trying to resolve '/socket.io/socket.io.js' from my Node server. I can't determine why.
My server configuration looks like this:
var express = require('express')
, engine = require('ejs-locals')
, app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
// use ejs-locals for all ejs templates:
app.engine('ejs', engine);
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs'); // so you can render('index')
app.use(express.static(__dirname + '/public'));
//define routes
...
app.listen(3000);
//socket io
io.sockets.on('connection', function (socket) {
socket.on('set nickname', function (name) {
socket.set('nickname', name, function () {
socket.emit('ready');
});
});
socket.on('msg', function () {
socket.get('nickname', function (err, name) {
console.log('Chat message by ', name);
});
});
});
At the client I have this:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
I am testing this locally (port: 3000). The Socket code is basically ripped off of the socket.io example to get something working. I have reviewed other posts and can't seem to find where I'm going wrong. Can someone help?
Thanks
Got it!
The HTTP server needs to be listing on the port (3000 in this case.) I then removed the app.listen(3000) as the address will already be in use and is not needed.
Thanks!
var express = require('express')
, engine = require('ejs-locals')
, app = express()
, http = require('http')
, server = http.createServer(app).listen(3000)
, io = require('socket.io').listen(server);

missing socket.io.js

when starting app.js I get
$ node app.js
info: socket.io started
however, running index.html it says that it's missing
GET http://localhost:3000/socket.io/socket.io.js 404 (Not Found) localhost:5
Uncaught ReferenceError: io is not defined
I used npm install socket.io express
app.js
var express = require('express')
, http = require('http');
var io = require('socket.io');
var app = express()
, server = require('http').createServer(app)
, io = io.listen(server);
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.use(express.bodyParser());
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
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>
Your code looks a bit messed up. Got it to work by changing it to this:
var express = require('express')
, http = require('http')
, app = express()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server)
;
app.configure(function(){
app.use(express.bodyParser());
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
server.listen(process.env.PORT || 3000);

nodejs, socket.io: how to get request and response from socket function?

i m creating chat application, using nodejs (0.8.15), express (>3.0) framework and mongodb for register users.
var express = require('express')
, http = require('http')
, path = require('path')
, io = require('socket.io');
var app = express()
, server = http.createServer(app)
, io = io.listen(server);
app.configure(function() {
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('secret'));
app.use(express.session({cookie: {maxAge: 60000*100}}));
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function() {
app.use(express.errorHandler());
});
app.get('/chat', function(req, res) {
res.render('chat');
});
server.listen(app.get('port'), function() {
console.log("Express server listening on port " + app.get('port'));
});
io.sockets.on('connection', function (socket) {
socket.on('start-chat', function() {
// here i need to know req and res
// for example, i need to write:
// socket.username = req.session.username;
});
});
Q: How to get res and req objects to work with them when chatting like on code above? or am i going wrong way of creating chat with user auth?
thank you!
EDITED: answer is here
http://www.danielbaulig.de/socket-ioexpress/
You need to use authorization.
var socketIO = require('socket.io').listen(port);
socketIO.set('authorization', function(handshakeData, cb) {
//use handshakeData to authorize this connection
//Node.js style "cb". ie: if auth is not successful, then cb('Not Successful');
//else cb(null, true); //2nd param "true" matters, i guess!!
});
socketIO.on('connection', function (socket) {
//do your usual stuff here
});
You cannot get res and req objects in a socket.io handler, as they simply do not exist - socket.io is not normal http.
Instead, what you can do is authenticate users and assign them a session auth token (a key that identifies that they're logged in and who they are).
Then the client can send the auth token along with every socket.io message, and the server-side handler can just check the validity of the key in the database:
io.sockets.on('connection', function (socket) {
socket.on('start-chat', function(message) {
if (message.auth_token)
//Verify the auth_token with the database of your choice here!
else
//Return an error message "Not Authenticated"
});
on socket.io v1.0 and above you can get the req object like this
var req = socket.request;
var res = req.res;

Resources