ambelovsky / koa-socket-2

Socket.IO for Koa
https://www.npmjs.com/package/koa-socket-2
98 stars 14 forks source link

app.listen vs http.createServer #5

Closed braksator closed 5 years ago

braksator commented 7 years ago

The example code uses app.listen but I'm using the http.createServer method outlined here: https://github.com/koajs/koa/blob/master/docs/api/index.md#applisten

This lets socket.io to work:

app.listen(port);

This doesn't work:

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

I figured perhaps the section on Attaching To Existing Projects would get me out of this jam (https://www.npmjs.com/package/koa-socket-2#attaching-to-existing-projects)

So I added the last two code blocks (from // If you had manually... onwards) but that just tries to start a second server on the same port which doesn't work.

I'm not sure what to do here.

braksator commented 7 years ago

Oh, ok just got rid of the original listen() calls.

I got it working like so:

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

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

if (/* my ssl conditions to check keys/certs */) {
  https.createServer(app.callback());
  app.listen(sslPort);
}

At least the http part works, I don't have keys/certs set up to test SSL yet.

I would still appreciate any comments, feedback, or suggestions to make this more succinct. Cheers!

ambelovsky commented 7 years ago

Hey Braksator,

You've got it. As convoluted as it is, that's currently the solution. There is not yet a convenience function for this behavior, but I'll put it on the list.

// *If* you had manually attached an `app.server` yourself, you should do: 
app.listen = function() {
  app.server.listen.apply(app.server, arguments);
  return app.server;
}

/* YOUR HTTP SERVER CODE HERE */

// app.listen is mapped to app.server.listen, so you can just do: 
app.listen( process.env.PORT || 3000 );