Skip to content
Advertisement

Socket.io error hooking into express.js

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…

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement