2017-04-18 2 views
0

익스프레스 js 응용 프로그램 (express 생성기에서 작성)에 socket.io를 통합하려고합니다.Express js의 Socket.io : 미들웨어 기능이 필요하지만 정의되지 않았습니다.

Here is the answer i've followed

그러나 그것은 작동하지 않았다. 내가 app.use('/', require('./routes/index')(app.io))app.use('/', index);을 수정하면

추가 bin/www

에 다음과 같은; app.js 파일에 내가 Router.use 미들웨어 기능을 필요로하는 다음과 같은 오류를

*

을 가지고 있지만

을 정의되지있어 *

답변

3

여기 당신이 소켓을 구현할 수있는 방법이다. 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 generator의 route 내에서 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 객체를 전달하는 더 좋은 방법이 많이 있지만 이러한 결정은이 질문의 범위를 벗어나는 것 같습니다.

+0

어디에서 추가 할 수 있습니까 ?? –

+0

'routes/index.js'에 io 오브젝트를 사용하고 싶지만, yr 코드에 따라 모든 것이'app.js' 파일에 있습니다. –

+0

이러한 변경은 project_root/bin/www 내에서 수행 할 수 있습니다. – user2263572

관련 문제