我看到很多人都有像我这样的问题,但我找不到答案 我使用Express 3.2.6,我想添加Socket.io。
服务器端:
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, index = require('./routes/index')
, http = require('http')
, path = require('path')
, nunjucks = require('nunjucks')
, mongoose = require('mongoose')
, validator = require('validator');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'nunjucks');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var socket = io.connect();
我认为我犯了很多错误。 但我不明白为什么节点会发给我:
var socket = io.connect();
^
TypeError: Object #<Server> has no method 'connect'
at Object.<anonymous> (C:\Users\Damien\workspace\project\app.js:35:17)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
更新
我改为express.io
http://express-io.org/
但我有一个问题。我没有错误消息,但我的服务器和我的客户端 似乎没有沟通。
客户端部分:
<script src="https://cdn.socket.io/socket.io-1.2.1.js"></script>
<script type="text/javascript">
document.onload = function(){
var socket = io.connect("http://127.0.0.1:8080");
//Emit ready event.
socket.emit('ready');
//Listen for the talk event.
socket.on('talk', function(data) {
console.log(data);
});
};
</script>
服务器部分:
var app = require('express.io')()
var nunjucks = require('nunjucks')
var mongoose = require('mongoose')
var validator = require('validator');
var routes = require('./routes')
var index = require('./routes/index')
app.http().io()
app.set('view engine', 'nunjucks');
app.set('views', __dirname + '/views');
mongoose.connect( '' );
nunjucks.configure('views', {
autoescape: true,
express: app
});
var urlSchema = new mongoose.Schema({
long : String,
count : Number
}
);
//create model
var urlModel = mongoose.model('urls', urlSchema);
app.get('/', index.index);
//Setup the ready route, and emit talk event.
app.io.route('ready', function(req) {
req.io.emit('talk', {
message: 'io event from an io route on the server'
})
})
app.listen(8080);
我不明白客户端控制台中没有任何内容。
答案 0 :(得分:0)
我发现了问题:
<script src="https://cdn.socket.io/socket.io-1.2.1.js"></script>
必须
<script src="/socket.io/socket.io.js"></script>