我无法使用socket.io发出任何消息

时间:2016-10-24 00:05:43

标签: node.js sockets express socket.io

我正在尝试建立一个聊天室,我将用户会话从passport + express传递给socket.io。但现在我无法发出任何消息。 io.on似乎没有连接。

我没有收到任何错误消息

这是我的代码

var express = require('express');
var app = express();
var server = require('http').Server(app);

var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');

var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');

// Add connect-mongo to project - npm install connect-mongo
var MongoStore = require('connect-mongo')(session);

var configDB = require('./config/database.js');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var chatdb = require('./app/models/chat.js');

// configuration ===============================================================
// NOTE: This might need to be put into a callback/promise inside an initialize function
var db = mongoose.connect(configDB.url); // connect to our database

require('./config/passport')(passport); // pass passport for configuration

// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms

app.set('view engine', 'ejs'); // set up ejs for templating


// required for passport
app.use(session({ secret: 'secret' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
app.use(express.static(__dirname + '/views'));
app.use(express.static(__dirname + '/public'));

// Create a MongoDB storage object
var mongoStore = new MongoStore({
  mongooseConnection: db.connection,
  collection: configDB.sessionCollection,
});

// Intercept Socket.io's handshake request
io.use(function (socket, next) {
  // Use the 'cookie-parser' module to parse the request cookies
  cookieParser('secret')(socket.request, {}, function (err) {
      // Get the session id from the request cookies
      var sessionId = socket.request.signedCookies ? socket.request.signedCookies['session-key'] : undefined;

      if (!sessionId) return next(new Error('sessionId was not found in socket.request'), false);

      // Use the mongoStorage instance to get the Express session information
  mongoStore.get(sessionId, function (err, session) {
      if (err) return next(err, false);
      if (!session) return next(new Error('session was not found for ' + sessionId), false);

      // Set the Socket.io session information
      socket.request.session = session;
      console.log(session);
      console.log(socket.request.user);

      // Use Passport to populate the user details
      passport.initialize()(socket.request, {}, function () {
      passport.session()(socket.request, {}, function () {
      // This will prohibit non-authenticated users from connecting to your
      // SocketIO server.
  if (socket.request.user) {
  next(null, true);
  } else {
  next(new Error('User is not authenticated'), false);
  }
    });
    });
    });
    });
});

// socket.io
io.on('connection', function (socket) {
  console.log('a user connected');

  socket.on('chat message', function(msg){
    console.log('a use connected');
    var name = "efe";
    chatdb.saveMsg({name: name, msg: msg}, function(err){
      if(err) throw err;
      io.emit('chat message', msg);
      });
    });

  socket.on('disconnect', function () {
  console.log('user disconnected');
});
});

// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport

// launch ======================================================================
http.listen(port);
console.log('The magic happens on port ' + port);

这是我的客户端代码。

<!doctype html>
<html>
  <head>
    <title>chat message</title>

    <link rel="stylesheet" href="/css/chat.css" type="text/css"/>
  </head>
  <body>
    <div class="messages"><br/><br/><br/><br/><br/><br/> </div>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="https://cdn.socket.io/socket.io-1.3.7.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      var socket = io();
      $('form').submit(function(){
        socket.emit('chat message', $('#m').val());
        $('#m').val('');
        return false;
      });
      socket.on('chat message', function(msg){
        $('.messages').append($('<div class=bubble><br/>').text(msg));
      });
    </script>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

这是我的修复

var express = require('express');
var app = express();
var server = require('http').Server(app);

var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');

var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');

// Add connect-mongo to project - npm install connect-mongo
var MongoStore = require('connect-mongo')(session);

var configDB = require('./config/database.js');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var chatdb = require('./app/models/chat.js');

// configuration ===============================================================
// NOTE: This might need to be put into a callback/promise inside an initialize function
var db = mongoose.connect(configDB.url); // connect to our database

require('./config/passport')(passport); // pass passport for configuration

// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms

app.set('view engine', 'ejs'); // set up ejs for templating
var mongoStore = new MongoStore({
  mongooseConnection: db.connection,
});
app.use(session({
  secret: 'secret',
  clear_interval: 900,
  cookie: { maxAge: 2 * 60 * 60 * 1000 },
  store: mongoStore,
}));



// required for passport
app.use(session({ secret: 'secret' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
app.use(express.static(__dirname + '/views'));
app.use(express.static(__dirname + '/public'));




// Intercept Socket.io's handshake request
io.use(function(socket, next) {

    // Use the 'cookie-parser' module to parse the request cookies
    cookieParser('secret')(socket.request, {}, function(err) {

        // Get the session id from the request cookies
        var sessionId = socket.request.signedCookies ? socket.request.signedCookies['connect.sid'] : undefined;

        if (!sessionId) return next(new Error('sessionId was not found in socket.request'), false);

        // Use the mongoStorage instance to get the Express session information
        mongoStore.get(sessionId, function(err, session) {
            console.log('efe');
            if (err) return next(err, false);
            if (!session) return next(new Error('session was not found for ' + sessionId), false);

            // Set the Socket.io session information
            socket.request.session = session;
            console.log(sessionId);
            console.log(socket.request.user);

            // Use Passport to populate the user details
            passport.initialize()(socket.request, {}, function() {
                passport.session()(socket.request, {}, function() {
                    // This will prohibit non-authenticated users from connecting to your
                    // SocketIO server.
                    if (socket.request.user) {
                        next(null, true);
                    } else {
                        next(new Error('User is not authenticated'), false);
                    }
                });
            });
        });
    });
  });

// socket.io
io.on('connection', function(socket) {
    console.log('a user connected');

    socket.on('chat message', function(msg) {
        console.log('a use connected');
        var name = "efe";
        chatdb.saveMsg({
            name: name,
            msg: msg
        }, function(err) {
            if (err) throw err;
            io.emit('chat message', msg);
        });
    });

    socket.on('disconnect', function() {
        console.log('user disconnected');
    });
});

// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport

// launch ======================================================================
http.listen(port);
console.log('The magic happens on port ' + port);