Socket.io错误挂钩到express.js

时间:2014-07-28 16:55:16

标签: javascript node.js express socket.io

我试图将socket.io和express.js挂钩在一起:

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);

在第var io = require('socket.io').listen(app);行:我收到错误:

Error: You are trying to attach socket.io to an expressrequest handler function. Please pass a http.Server instance.

在SO / google上似乎没有关于此错误的任何内容......

3 个答案:

答案 0 :(得分:63)

您应该使用http模块:

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

您可以在文档中找到更多详细信息:http://socket.io/docs/#using-with-express-3/4

答案 1 :(得分:1)

您无需使用http模块就可以做到

app.listen返回可用于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);

答案 2 :(得分:1)

要使 socket.io 与 express 一起工作,您需要一个服务器实例,因此将它附加到 socket.io

我将使用 express 的 .listen 方法,因为它返回一个 http.Server 对象。阅读文档 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);