Express and socket.io - server declaration and start
I never really understood how the following 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(){});
Could you help me understand what's going on here? And is one approach preferable to the other (and under what circumstances)? Thank.
+3
source to share
1 answer
The passages are not equivalent. Some are 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 provides a handler function app
that you pass to the http server. Socket.io expects you to pass an http server to it to connect it.
0
source to share