Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allowing additional hooks to server on connection #24

Open
jethrokuan opened this issue Dec 8, 2016 · 3 comments
Open

Allowing additional hooks to server on connection #24

jethrokuan opened this issue Dec 8, 2016 · 3 comments

Comments

@jethrokuan
Copy link

It seems like the connection event is not exposed, I can't access it. For example, I want to do:

  ctx.websocket.on('connection', function(ws, req){
    console.log("connected");
   )}

but this doesn't seem to work.

@skomarfaruque
Copy link

Same problem here. only message is allowed.Can someone please describe a bit please!?

@kentnek
Copy link

kentnek commented Apr 12, 2018

I think the connection event is fired when the root route / is accessed. I got it to work:

const Router = require('koa-router');
const ws = new Router();
...

ws.get('/', (ctx, next) => {
    ctx.websocket.send("Hello client!");

    ctx.websocket.on('close', function () {
        console.log("Client left.");
    });
});

@david-cannady
Copy link

david-cannady commented May 17, 2018

The connection event is fired before before any middleware(your router) is executed. If you have access to ctx then you have already connected. More precisely, if you have access to a WebSocket object then you have already connected the socket (unless you are acting as a client). The on('connection', ...) should be on the server object not the websocket.
For instance, if you are using ws directly then you'd call on('connection', ...) on the WebSocket.Server object not the WebSocket object.
With that said, the WebSocket.Server object is available on app.ws.server, but unfortunately that is not populated until you have called the listen() function. Too little, too late.
If you want to call on('connection', ...) you'd basically have to rewrite KoaWebSocketServer.prototype.listen to add your calls. Kinda of a pain,
This project would be more robust if it supported KoaWebSocketServer.on() for 'error' and 'connection'. If I have some free time, I'll likely contribute.
Though considering the activity of this repo, it might not be merged for a while if ever.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants