nodejs socket.io express handshake error - node.js

I try to create a real time app by socket.io.
Server side:
var express = require('express');
var io = require('socket.io');
var engine = require('ejs-locals');
var app = express()
, server = require('http').createServer(app)
, io = io.listen(server);
app.engine('ejs', engine);
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.redirect('/login')
});
app.use(express.static(__dirname + '/public'));
app.listen(3001);
io.sockets.on('connection', function (socket) {
console.log('Client connected...');
socket.on('send_login_data', function (data) {
console.log(data);
});
});
Client side:
var socket = io.connect('http://localhost:3001');
socket.on('connect_failed', function(){
console.log('Connection Failed');
});
socket.on('connecting', function () {
console.log('connecting...');
});
socket.on('connect', function () {
console.log('connected!');
});
I caught the next error:
GET http://localhost:3001/socket.io/1/?t=1447539302809 404 (Not Found)
As I understand, it's a handshake error.
How can I fix it?
Thanx.

First off, make absolutely sure there are no errors showing anywhere in case some module isn't installed properly.
Then, make sure you have the same version number of socket.io on client and server and that you have the server-side version installed on the server.
Then, I've seen folks have issue with this before, even when following the instructions on the socket.io web site and it's never been clear exactly what was wrong with that sequence. But, what I know is that this sequence will work:
var express = require('express');
var app = express();
var server = app.listen(3001);
var io = require('socket.io').listen(server);
See related issues: Where is my client side socket.io? and Node + Socket.io Connection issue
I don't know if this is causing the issue or not, but you are attempting to redefine the io variable when it has already been declared in this:
var io = require('socket.io');
var app = express()
, server = require('http').createServer(app)
, io = io.listen(server);
The second reference to io = io.listen(server) is essentially this:
var io = require('socket.io');
var app = express();
var server = require('http').createServer(app);
var io = io.listen(server);
Which is not correct Javascript. Again, may not be causing your issue, but it is not technically proper Javascript.

Related

node socketIO upgrade 0.9.17 to 1.34 breaks application

My app no longer works after upgrading socketIO from 0.9.17 to 1.3.4.
Can anyone help? this is my app
Normally when I launch I should see
info -socket.io started
Now I see nothing, no errors either.
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server,{transports:['flashsocket', 'websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']});
var port = Number(8080);
server.listen(port);
app.use(express.static(__dirname + '/'));
var temp;
var _this = this;
io.on('connection', function (socket) {
console.log('connection '+socket)
socket.on("data",function(d){console.log('data from flash: ',d);});
socket.emit("message","wtfwtwftwftwf hello from server");
socket.on('disconnect', function (socket) {
console.log("disconnect");
});
console.log('_this ='+_this);
_this.socket=socket;
});
The current socket.io documentation suggests this which is slightly different than what you have:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server, {transports:['flashsocket', 'websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']});
var port = Number(8080);
server.listen(port);
app.use(express.static(__dirname + '/'));
var temp;
var _this = this;
io.on('connection', function (socket) {
console.log('connection '+socket);
socket.on("data",function(d){console.log('data from flash: ',d);});
socket.emit("message","wtfwtwftwftwf hello from server");
socket.on('disconnect', function (socket) {
console.log("disconnect");
});
console.log('_this ='+_this);
_this.socket=socket;
});
Also, your assignment of _this.socket=socket; looks troublesome because this appears like it would only ever work for one client connected at a time. As soon as you have more than one webSocket connection, the second connection would overwrite the first.
Also, you should make absolutely sure you're using compatible socket.io libraries on client and server (e.g. same version on both ends).

Express-Generator - Including socket.io (bin/www)

I've always been a bit of a Perl/PHP sorta guy, but I fancy a change and Node JS seems like the right place for me to go next.
I've watched a good few hours of tutorials on YouTube and read some posts on here - but I have come up a bit stuck.
I'd like to include socket.io in my express-generated application (v4.10.6).
At the same time though, I don't really want to include the socket.on(...) statements in one file - i'd much rather split it out like you would with a route.
Given that the express-generated app is started in bin/www, i'm confused as to where I need to require('socket.io') and point all the 'on' events to.
This post on stackoverflow, I think may answer my question - but it suggests all the socket handlers are in the ./sockets/base.js file - and I am confused by the Gofilord's response to the answer.
Please forgive my ignorance here - this is all a bit alien to me at the moment, and thank you, as always for taking the time to read this and your help.
/bin/www
#!/usr/bin/env node
var debug = require('debug')('rhubarb');
var app = require('../app');
app.set('port', process.env.PORT || 1127);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
Its typical to require socket.io in app.js and then to tell your io sever to listen to your application. Using the example you posted, that would look like this:
var debug = require('debug')('rhubarb');
var app = require('../app');
var server = require('http').Server(app);
var io = require('socket.io')(server);
app.set('port', process.env.PORT || 1127);
var server = server.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
The socketio docs do a really good job of explaining this. Here's an example from their homepage:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Update:
I typically modularize socketio setup by creating a lib called io.js in /lib with something like this:
module.exports = function(server){
var io = require('socket.io')(server);
// catch errors
io.on('error', function(err){
throw err;
})
// Set Socket.io listeners by creating a socket.io middleware
// attachEventlisteners would live in `/controllers`
io.use(attachEventlisteners);
io.on('connection', function (socket) {
// do things
});
return io; // so it can be used in app.js ( if need be )
}
then in app.js i can simply pass the server in when I require it:
var io = require('./lib/io')(server);
You dont need to do any thing further in app.js since everything is setup in /lib/io.js, but if you wanted to you could because the io server is returned.

express and socket.io - declaration and starting server

I've never understood how the below codes are equivalent:
Code 1:
var app = require("express")();
var server = require('http').Server(app);
var io = require('socket.io').listen(server);
...
io.use(...);
...
server.listen(3000, function(){});
Code 2:
var app = require("express")().listen(3000);
var io = require("socket.io")(app);
...
io.use(...);
Code 3:
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
...
io.use(...);
...
server.listen(3000, function(){});
Can you please help me understand what is happening here ? And is one approach preferable over the other (and under what circumstances) ? Thanks.
The snippets are not equivalent. Some are from older versions of express and socket.io and some are more recent. I would use a modified example from the socket.io documentation.
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
/* Setup Express */
app.get('/', function (req, res) {
...
});
/* Setup Socket.io */
io.on('connection', function (socket) {
...
});
server.listen(3000);
Express now just exposes a handler function app which you pass to an http server. Socket.io expects you to pass it an http server for it to plug into.

How to connect Two Socket.io Node Application using Socket.io-client in Node js

In my application i need to connect two socket.io node applications.Using socket.io-client we can do like this.But i don't know how socket.io-client works and where to include that.
First Node Application
var express = require('express')
, http = require('http');
var app = express();
app.use(function (req, res) {
app.use(express.static(__dirname + '/public'));
});
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(3000);
io.sockets.on('connection',function(socket){
socket.on('eventFiredInClient',function(data){
socket.emit('secondNodeAppln',data);// i need to get this event in my 2nd node application how can i do this by using socket.io-client
});
});
Second Node Application
var express=require('express');
var http=require('http');
var app=express();
app.configure(function(){
app.use(express.static(__dirname + '/public'));
});
var server = http.createServer(app);
var serverAddress = '127.0.0.1';
var serverPort = 3000; //first node appln port
var clientio = require('socket.io-client');
var socket = clientio.connect(serverAddress , { port: serverPort });
socket.on('connect', function(){
console.log('connected');
});
socket.on('disconnect', function(){
console.log('disconnected');
});
var io = require('socket.io').listen(server);
server.listen(6509);
//here i need to get the 'secondNodeAppln' event raised in first node application.How can i do this.
You need to create a socket.io client in your first app:
var io = require('socket.io').listen(server); // this is the socket.io server
var clientio = require('socket.io-client'); // this is the socket.io client
var client = clientio.connect(...); // connect to second app
io.sockets.on('connection',function(socket) {
socket.on('eventFiredInClient',function(data) {
client.emit('secondNodeAppln', data); // send it to your second app
});
});
And in your second app, just listen for those events:
io.sockets.on('connection', function (socket) {
socket.on('secondNodeAppln', function(data) {
...
});
});
There's a bit of a race condition because the code above doesn't wait for a connect event on the client socket before passing events to it.
EDIT see this gist for a standalone demo. Save the three files to a directory, start the servers:
node serverserver &
node clientserver
And open http://localhost:3012 in your browser.

Can't find socket.io.js

I'm making a web-app that makes use of nodejs, mongodb, socket.io, express and mongoose.
I can start my server and correctly get the wanted html file in my browser when browsing to my localhost.
The problem I have is getting my socket.io to work.
On my server side everything works fine : I get " info - socket.io started " in my terminal.
But when surfing to my browser I get this in my browser console
Failed to load resource: the server responded with a status of 404 (Not Found)
Uncaught ReferenceError: io is not defined
This is how i connect to socket.io.js
<script src="/socket.io/socket.io.js"></script>
and my map structure looks like this:
map
-app.js
-public
--index.html
-node_modules
--socket.io
--mongodb
--express
--jade
--mongoose
Does anyone knows what the mistake is I've made?
(it's actually the same problem as here: Node.js socket.io.js not found or io not defined )
Thanks in advance!
EDIT:
My code on the server side is this:
var app= require('express').createServer();
var io = require('socket.io').listen(app);
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/db');
app.listen(3030);
console.log("server started");
app.get('/',function(req,res){
res.sendfile(__dirname + '/public/index.html');
});
io.sockets.on('connection',function(socket){
console.log("connection made");
});
The first log, gets logged in the terminal ("server started"), but the second one ("connection made") doesn't get logged. So the connection isn't made.
I thought that was because of the wrong "set up" in my client side.
Check out the express migration guide 2->3
https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x
Something like this should work
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/db');
server.listen(3030);
console.log("server started");
app.get('/',function(req,res){
res.sendfile(__dirname + '/public/index.html');
});
io.sockets.on('connection',function(socket){
console.log("connection made");
});
var app = express();
app.set('port', process.env.PORT || 3000);
...
var server = http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
var io = socket.listen(server);
io.sockets.on('connection', function () {
console.log('hello world im a hot socket');
});

Resources