mattstyles / koa-socket

Sugar for connecting socket.io to a koa instance
242 stars 50 forks source link

How to attach to an already created server? #35

Open andrewc89 opened 7 years ago

andrewc89 commented 7 years ago

I have recently implemented (koa-sslify)[https://github.com/turboMaCk/koa-sslify] which requires the use of https.createServer instead of app.listen in order to pass SSL options to the server.

I can't find any example of how to attach koa-socket to the koa app when using the createServer method.

Here is the code:

let app = new Koa();
let io = new IO();

io.on('connection', (ctx) => {
    store.dispatch(socketConnected(ctx));

    ctx.socket.on('action', (data) => {
        try {
            let action = JSON.parse(data);
            action.meta = action.meta || {};
            action.meta.ctx = ctx;
            store.dispatch(action);
        } catch (err) {
            log.logger.info(err);
        }
    });

    ctx.socket.on('disconnect', () => {
        store.dispatch(socketDisconnected(ctx));
    });
});

let sslOptions = {
    pfx: fs.readFileSync(config.pfxPath),
    passphrase: config.pfxPassphrase,
};

http.createServer(app.callback()).listen(config.port);
https.createServer(sslOptions, app.callback()).listen(config.sslPort);

io.attach(app);

Looking at the source code I see that the server is assigned to a server property on the app object:

app.server = http.createServer( app.callback() )

I have tried to mimic the behavior in the attach function but with no luck.

I am using the following versions:

$ npm ls | grep koa
├─┬ koa@1.4.0
│ ├── koa-compose@2.5.1
│ ├── koa-is-json@1.0.0
├─┬ koa-json-logger@1.0.2
├─┬ koa-router@5.4.1
├─┬ koa-socket@4.4.0
│ ├─┬ koa-compose@3.1.0
├── koa-sslify@1.1.0
├─┬ koa-static-server@0.1.8
│ └─┬ koa-send@1.3.1
andrewc89 commented 6 years ago

I was eventually able to figure this out. I basically copied the code from here in the attach function in the koa-socket source. Here is the relevant parts of my code:

let app = new Koa();
let io = new IO();

let sslOptions = {
    pfx: fs.readFileSync(config.pfxPath),
    passphrase: config.pfxPassphrase,
};

http.createServer(app.callback()).listen(config.port);

app.server = https.createServer(sslOptions, app.callback());
app.server.listen(config.sslPort);

app.listen = function listen() {
    app.server.listen.apply( app.server, arguments );
    return app.server;
};

io.attach(app);

I'm not sure the best way to handle this, but I think the attach function should be updated or at least the README.