Socket.IO error 'listen()' method expects

2019-03-17 22:22发布

I began learning Node.js today and I'm a little stuck.

Following this example, I get the following error when I try executing the js file:

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

I don't know how to fix this.

UPDATE

Error resulting from Bill's modified code:

/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条回答
ゆ 、 Hurt°
2楼-- · 2019-03-17 22:52

There was a change to how you initialize express apps between versions 2 and 3. This example is based on version 2 but it looks like you've installed version 3. You just need to change a couple of lines to set up socket.io correctly. Change these lines:

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

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

to this:

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);
查看更多
做自己的国王
3楼-- · 2019-03-17 23:09

Simplified to three lines of code that would be:

var server = require('http').createServer(require('express')()),
io = require('socket.io').listen(server);
server.listen(8080);
查看更多
登录 后发表回答