Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 678
alyx Avatar asked Jul 28 '14 16:07

alyx


People also ask

Can you use Socket.IO with Express?

Socket.IO can be used based on the Express server just as easily as it can run on a standard Node HTTP server. In this section, we will fire the Express server and ensure that it can talk to the client side via Socket.IO.

Can I use Socket.IO without node js?

Is it possible to use socket.io without any node. js dependencies? The short answer is yes. You will however have Flash dependency.


1 Answers

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

like image 93
Oleg Avatar answered Sep 28 '22 06:09

Oleg