私はsocket.ioとexpress.ioの間を行き来しましたが、名前空間を使用したいので、Express 4でsocket.ioに落ち着きました。
私は Socket.io を使用して Express 4 サーバーを使用するいくつかの例に取り組んできましたが、ほとんどの例はすべてが含まれる 1 つのファイルに基づいています。簡単にするためにすべてのコードを分離しようとしていますが、Socket.io (または場所) を追加する方法について途方に暮れています。
Cluster を使用し、基本的に server.js を呼び出す index.js があります。
var server = require( "./server.js" );
var cluster = require('cluster');
var webApp={
run: function(){
console.log('Starting: Server');
server.listen();
}
};
if(cluster.isMaster){
cluster.fork();
cluster.on('exit',function(worker){
console.log('Worker ' + worker.id + ' died..');
setTimeout( function () { cluster.fork(); }, 1000 );
});
} else{
try {
webApp.run();
}
catch(e)
{
console.log(e);
process.exit(1);
}
process.on('uncaughtException', function(err){
console.log(err);
process.exit(1);
});
process.on( 'SIGINT', function () {
console.log( "\n SIGINT (Crtl-C)" );
//Kill worker
cluster.disconnect();
process.exit(1);
});
}
次に、server.js ファイルを呼び出します。
var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var config = require('./config/config.js');
var router = require('./routes');
var Server = Object.subClass({
/**
* Constructor
*/
init:function(){
this.appServer = express();
var that = this;
var appServer = this.appServer;
appServer.use(express.static(__dirname + '/public'));
appServer.set('views', path.join(__dirname, 'views'));
appServer.set('view engine', 'ejs');
appServer.use(bodyParser.urlencoded({ extended: true }));
appServer.use(bodyParser.json());
appServer.get('/',router.root);
},
/**
* Listener HTTP
*/
listen:function(){
var port = config.rest.port;
console.log(':: on port:' + port);
this.appServer.listen(port);
}
});
module.exports = new Server();
これは「/」であり、routes.js ファイルで定義されています。ページは正常に読み込まれますが、サーバー側の socket.io はどこに追加すればよいですか? また、routes.js ファイルまたは読み込まれるページの JavaScript に socket.io 名前空間定義を追加する必要がありますか?
ソケットの使用方法が非常に多いため、マルチファイル アプローチに最適なアプローチを見つけることができないようです。
私はぐるぐる回っているように見えるので、どんな助けも素晴らしいでしょう。
土曜日をお楽しみください :)
再度、感謝します。