这是我的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
我在这里堆得太多了......这有什么不对? 也许有人有同样的问题...
答案 0 :(得分:0)
尝试socket.io
监听server
端口,将1111
定义为服务器端口,将8080
定义为socket.io
,您的应用程序可供访问在localhost:1111
。
简短的例子
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
io.listen(server);