Sunday 14 May 2017

Socket.io generates ID twice

I've trying to get socket.io to work with express in which I have the following code

server.js

var http = require('http');
var cookieParser = require('cookie-parser');

var webpackMiddleware = require("webpack-dev-middleware");
var webpack = require('webpack');
var path = require('path');
var fs = require('fs');

var express = require('express');
var session = require('express-session');

var config = require('./webpack.dev.config');

var app = express();
app.set('port', process.env.PORT || 3000);

var server = http.createServer(app);
var sio = require('./socket')(server).io;

var compiler = webpack(config);

app.use(
    webpackMiddleware(compiler, {
        noInfo: true,
        publicPath: config.output.publicPath
    })
)

var sessionMiddleware = session({
    genid: req => {
        let id = Math.random().toString(36).substring(7);
        console.log("GENID: ", id);
        return id;
    },
    secret: 'ssshhhhh',
    resave: true,
    saveUninitialized: true
});

sio.use((socket, next) => {
    sessionMiddleware(socket.request, socket.request.res, next);
});

app.use(sessionMiddleware)

app.get('/', function(req, res) {
    res.status(200).sendFile(__dirname + '/index.html');
});

server.listen(app.get('port'), (err) => {
    if (err) {
        console.error(err);
    }
    console.log('Listening on port: ' + app.get('port'));
});

socket.js

module.exports = function (server) {

    this.io = require('socket.io')(server);
    io.set("origins", "*:*");

    // On someone connected
    io.sockets.on('connection', function(socket) {
        let { id } = socket.request.session; 
        console.log("Session ID: ", id);
    }.bind(this));

    return this;
}

And the front end code is a simple Angular2 application as follows:

app.component.ts

@Component({
  selector: 'my-app',
  templateUrl: './app.template.html',
  styles: [ APPSTYLES ]
})
export class AppComponent  {

  private hostUrl = window.location.protocol + "//" + window.location.hostname + ":" + window.location.port;
  private ws = io(this.hostUrl);
}

The problem I am getting is the first time the page is requested, the genid is called twice and from then on it isn't. I would expect it to only be called once. The console log looks something like this

GENID: 8bdujsg51j26mtca6ecdi
Session ID: 8bdujsg51j26mtca6ecdi
GENID:  327ekky9u9v5hjb57b9 // First request
Session ID: 327ekky9u9v5hjb57b9 // Second request
Session ID: 327ekky9u9v5hjb57b9 // Third request

I need the session id to be the same from the first request. Help much appreciated.



via slim1801

No comments:

Post a Comment