如何使用socket.io正确发出事件?

时间:2015-07-06 14:02:40

标签: javascript node.js socket.io

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
var expressCookieParser = require('cookie-parser');
var expressSession = require('express-session');

var COOKIE_SECRET = 'very secret string';
var EXPRESS_SID_KEY = 'connect.sid';
var cookieParser = expressCookieParser(COOKIE_SECRET);
var sessionStore = new expressSession.MemoryStore();

app.use(expressSession({
    store: sessionStore,
    resave: false,              
    saveUninitialized: false,   
    secret: COOKIE_SECRET,      
    name: EXPRESS_SID_KEY       
}));

var messageHistory = '';
var userNick ='';



app.use(cookieParser);

app.get('/', function(req, res){
    res.sendFile(__dirname + '\\HTML\\loginWindow.html');
    req.session.isLogged = true;
    req.session.username = 'Hello.World';
});

app.get('/chat', function(req, res){    
    res.sendFile(__dirname + '\\HTML\\index.html');
});

app.get('/logout', function (req, res) {
    req.session.isLogged = false;
    delete req.session.username;
    req.session.destroy();

    res.sendFile(__dirname + '\\HTML\\loginWindow.html');
});

io.use(function(socket, next) {
    var request = socket.request;

    if(!request.headers.cookie) {
        console.log('No cookie transmitted.');
    }

    cookieParser(request, {}, function(parseErr) {
        if(parseErr) { return next(new Error('Error parsing cookies.')); }

        var sidCookie = (request.secureCookies && request.secureCookies[EXPRESS_SID_KEY]) ||
                        (request.signedCookies && request.signedCookies[EXPRESS_SID_KEY]) ||
                        (request.cookies && request.cookies[EXPRESS_SID_KEY]);

        sessionStore.load(sidCookie, function(err, session) {
            if (err) {
                return next(err);

            } else if(!session) {
                console.log('Session cannot be found/loaded');
                //io.emit('event') doesn't work here, how to do it?
            } else if (session.isLogged !== true) {
                console.log('User not logged in');

            } else {
                request.session = session;
                request.sessionId = sidCookie;

                return next();
            }
        });
    });
});

io.on('connection', function(socket){
    socket.on('login', function(nick){
        userNick = nick;
        console.log(userNick + " was logged!");
        io.emit('logged');

    });
      socket.on('chat message', function(msg){
          var message = userNick +': '+ msg;
          io.emit('chat message',message);
          messageHistory += message + " \n";
          fs.writeFile(__dirname +'/history.txt', messageHistory, function(err) {
              if(err) {
                  return console.log(err);
              }
          }); 
      });
});

http.listen(3000, function(){
console.log('listening on *:3000');
});

我尝试使用node.js编写一个简单的聊天应用程序。我的问题在于方法io.use。我想保护我的聊天,所以没有人可以使用域名/聊天链接输入它,但我真的不知道如何。我知道它必须以某种方式在io.use方法中完成,我尝试使用io.emit('back_to_main)简单地发送一个事件,但它似乎不起作用。我知道这段代码很垃圾,这是我第一次接触JS,但也许有人可以帮我解决这个简单的问题。

1 个答案:

答案 0 :(得分:0)

有两种方法可以做到这一点 1.使用以下模块link
2.使用可以在io.use中使用expresssession并将请求变量传递给它

 var req = socket.request;
        app.use(expressSession(req,{},function(req,res){
            next();
        }));