這裏是你如何實現插座。與明確的io。
var express = require('express')
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
//serve static files and index.html
app.use(express.static(__dirname + '/'));
app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); });
io.on('connection', function(socket){
//logic handled in here
});
http.listen(7000,function(){ console.log('listening on port: 7000'); });
上面的代碼有處理的index.html的服務一條路線,當然你可以用其他路由擴展您在任何其他應用程序的方法相同。
以下是如何在express生成器的路徑中訪問socket.io的方法。
在WWW:
var server = http.createServer(app);
var io = require('socket.io')(server);
module.exports = {io:io}
在index.js
router.get('/', function(req, res, next) {
var io = require('../bin/www')
console.log('I now have access to io', io)
res.render('index', { title: 'Express' });
});
注意,上面的例子,純粹是向您展示如何獲得index.js內訪問IO對象。有很多更好的方法需要socket.io並傳遞io對象,但這些決定似乎超出了這個問題的範圍。
我可以在哪裏添加? –
我想在'routes/index.js'中使用io對象,但是按照每年的代碼,一切都在'app.js'文件中執行 –
您可以在project_root/bin/www中進行這些更改。 – user2263572