これは私の app.js ファイルのスケルトンです。
私が理解していないのは、「ログ認証」を読み取って出力しない方法です。私はこれに従ったhttps://github.com/LearnBoost/socket.io/wiki/Authorizing
var express = require('express');
mongoose = require('mongoose');
var MongoStore = require('connect-mongo')(express);
app = express();
// costants
var SITE_SECRET = 'xxx';
// mongoose
mongoose.connect('mongodb://127.0.0.1/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
console.log('Mongoose connection is now opened');
});
// pass same objects from Express to Socket.IO so they match
var parseCookie = express.cookieParser(SITE_SECRET);
var store = new MongoStore({
mongoose_connection: mongoose.connection,
db: mongoose.connections[0].db
});
app.configure(function(){
app.set('host', '127.0.0.1');
app.set('port', 1111);
// init cookie-session
app.use(parseCookie);
app.use(express.session({
secret : SITE_SECRET
,store : store
,cookie: { maxAge: new Date(Date.now() + (1000*60*60*24*30*12)) }
}));
});
// create and start server
var server = require('http').createServer(app)
server.listen(app.get('port'));
// socket.io
var io = require('socket.io').listen(8080);
io.configure(function() {
console.log('log configure <-- it read this. ok!');
io.set('authorization', function(handshake, callback) {
console.log("log authorisation <-- but it doesn't read this. why??");
if (handshake.headers.cookie) {
parseCookie(handshake, null, function() {
handshake.sessionID = handshake.signedCookies['connect.sid'];
store.get(handshake.sessionID, function(err, session) {
callback(null, true);
});
});
} else {
// they client has no session yet, don't let them connect
callback('No session.', false);
}
});
});
clients = {};
io.sockets.on('connection', function (socket) {
// save to a global object
console.log('save session');
var session = socket.handshake.sessionID;
clients[session] = socket;
socket.on('disconnect', function() {
console.log('remove session');
delete clients[session];
});
});
// routes
app.get('/on', function(req, res){
var socket = clients[req.sessionID];
socket.on('test', function (data) {
console.log(data);
});
});
app.get('/emit', function(req, res){
var socket = clients[req.sessionID];
socket.emit('test', "ciao");
console.log("emit");
});
端末でサーバーを起動すると、次のように表示されます。
starting `node app.js`
Mongoose connection is now opened
info - socket.io started
log configure
そして、ページ「/on」をロードすると、エラーは次のようになります。
TypeError: Cannot call method 'on' of undefined
スタックしすぎてここにいる...これの何が問題なのですか?
たぶん誰かが同じ問題を抱えていた...