Socket.IO错误'listen()'方法在转移到Express 3.0后需要'http.Server'实例

时间:2012-10-06 22:13:03

标签: node.js express socket.io

我今天开始学习Node.js而且我有点陷入困境。

this示例后,当我尝试执行js文件时出现以下错误:

Warning: express.createServer() is deprecated, express
applications no longer inherit from http.Server,
please use:

  var express = require("express");
  var app = express();

Socket.IO's `listen()` method expects an `http.Server` instance
as its first parameter. Are you migrating from Express 2.x to 3.x?
If so, check out the "Socket.IO compatibility" section at:
https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x
   info  - socket.io started

我不知道如何解决这个问题。

更新

Bill修改后的代码导致的错误:

/home/sisko/NodeJS/nodeSerialServer/serialServer.js:24
var app     =   express()
                ^
ReferenceError: express is not defined
    at Object.<anonymous> (/home/sisko/NodeJS/nodeSerialServer/serialServer.js:24:12)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:492:10)
    at process.startup.processNextTick.process._tickCallback (node.js:244:9)

2 个答案:

答案 0 :(得分:36)

在版本2和版本3之间初始化express应用程序的方式发生了变化。此示例基于版本2,但看起来您已经安装了版本3.您只需要更改几行正确设置socket.io。改变这些行:

var app = require('express').createServer(),
    io = require('socket.io').listen(app),
    scores = {};                                

// listen for new web clients:
app.listen(8080);

到此:

var express = require('express'),
    app = express()
  , http = require('http')
  , server = http.createServer(app)
  , io = require('socket.io').listen(server);

// listen for new web clients:
server.listen(8080);

答案 1 :(得分:1)

简化为三行代码:

var server = require('http').createServer(require('express')()),
io = require('socket.io').listen(server);
server.listen(8080);