Socket.io error hooking into express.js
27,478
Solution 1
You can do it without using http
module
app.listen return a server instance you can use for socket.io
const express = require('express');
const app = express();
const server = app.listen(port, () => {
console.log("Listening on port: " + port);
});
const io = require('socket.io')(server);
Solution 2
You should use http
module:
var http = require('http');
var express = require('express'),
app = module.exports.app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server); //pass a http.Server instance
server.listen(80); //listen on port 80
//now you can use app and io
More details you can find in a documentation: http://socket.io/docs/#using-with-express-3/4
Solution 3
For socket.io to work with express, you need a server instance and therefore attach it to socket.io
I'll use .listen method of express since it returns an http.Server object. Read the docs here
const port = 3000,
app = require('express')(),
io = require('socket.io')();
// Your normal express routes go here...
// Launching app
const serverInstance = app.listen(port, () => {
console.log('App running at http://localhost:' + port);
});
// Initializing socket.io
io.attach(serverInstance);
Author by
alyx
Updated on February 07, 2021Comments
-
alyx about 3 years
I'm trying to hook socket.io and express.js together:
var socket = require('./socket_chat/socket.js'); var express = require('express'), app = module.exports.app = express(); var io = require('socket.io').listen(app); app.use(express.static(__dirname + '/app')); io.sockets.on('connection', socket);
At the line:
var io = require('socket.io').listen(app);
I'm getting an error:Error: You are trying to attach socket.io to an expressrequest handler function. Please pass a http.Server instance.
There doesn't seem to be anything on SO/google about this error...