Skip to content

How to attach to an already created server? #35

@andrewc89

Description

@andrewc89

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions