express and socket.io - declaration and starting server - node.js

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.

Related

How do I serve files from a lower directory with Express 3.x?

This answer made it clear how to serve files from a lower directory than the program's root, like so:
var path = require('path');
var express = require('express');
var app = express();
app.use(express.static(path.join(__dirname, '../public')));
This worked fine. Now I'm trying to set up a socket.io server like so:
const express = require('express');
const server = express();
const io = require('socket.io')(server);
and socket.io is throwing the error:
Error: You are trying to attach socket.io to an express request
handler function. Please pass a http.Server instance.
Which makes sense, because now on the socket.io documentation, it's asks for a setup like this:
const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', () => { /* … */ });
server.listen(3000);
But I don't know how to reconcile the old way of loading files from a lower directory like shown in the answer above with this new way of setting up express and socket.io, because where const app = require('express')(); as in the socket.io documentation, the error gets thrown TypeError: app.static is not a function.
How do I reconcile the now-outdated express path routing with the new express setup?
This is the way i did it in the old days of express 3.x.
var path = require('path');
var http = require('http');
var express = require('express');
var app = express();
app.use(express.static(path.join(__dirname, '../public')));
/* ... more routing logic, i.e app.get(...)*/
var server = http.createServer(app);
var io = require('socket.io')(server);
io.on('connection', () => {/* ... */});
server.listen(3000);
Hope it helps

socketio expressjs difference between two implementation

Is there any difference between this implementation:
this.app = express();
this.httpServer = http.createServer(this.app);
this.io = socket.listen(this.httpServer);
And this one:
this.app = express();
this.server = http.createServer(this.app);
this.io = socket(this.server);
Nopers, the second is a shorthand. :)
The first is provided in the event that you want to import/export the function from your express architecture
It seems like your other question was posted after this, is this still relevant?
Ok let's see what I've done that worked. I have seperated my sockets into a config file because my app.js was getting cluttered.
app.use(express.static(path.join(__dirname, '/')));
app.use(express.static(path.join(__dirname, '/node_modules/')));
var clients = {};
var server = http.createServer(app);
var io = require('socket.io')(server);
require('./config/app.socket.js')(io);
server.listen(8001);
io.set("origins", "*:*");
So, I cut out the middleman and pass the server directly to the socket.io import. then, I pass the reference to that io server to my app.socket.js file and listen to the server on port 8001
Here is my app.socket.js initialization
module.exports = function(io){
var clients = {};
var sockets;
io.on('connection', function (socket) {
sockets = socket;
socket.on(//your socket function)
}

nodejs socket.io express handshake error

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.

how to use Express 4 with Socket.io 0.9.x?

I am a ios developer, the Objc-Socket.io library is still support socket.io 0.9.x
I use Express 4.0 with my nodejs server:
server.js
var express = require('express')();
var io = require('socket.io');
io.listen(express);
But I run it in terminal, it throw me an error:
% node test
Socket.IO's `listen()` method expects an `http.Server` instance
as its first parameter. Are you migrating from Express 2.x to 3.x?
If so, check out the "Socket.IO compatibility" section at:
https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x
This code should do the trick:
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app).listen(1337);
var io = require('socket.io').listen(server);
io.on('connection', function(socket) {
//emit and listen messages
});
app.get('/', function(req, res) {
//do something
});

Connect2 and Socket.io

I'm trying to get connect and socket.io to work together nicely and simply. I have the following code on server side:
var connect = require('connect'),
io = require('socket.io');
var app = connect().use(connect.logger('dev'));
var sio = io.listen(app);
app.listen(8000);
when i open http://localhost:8000/socket.io/socket.io.js i'm get error:
Cannot GET /socket.io/socket.io.js
And Socket.IO not work, i'm trying copy file and load from another location, but socket.io requests do not reach the server
SOLUTION
if anyone comes to this issue, you need to wrap the connect/express app in a node http.Server. The app.listen() method is a convenience method for this and returns the server:
var io = require('socket.io');
var app = connect();
var server = app.listen(3000);
io.listen(server);
or the following is equivalent:
var io = require('socket.io');
var http = require('http');
var app = connect();
var server = http.createServer(app);
server.listen(3000);
io.listen(server);

Resources