koa-websocket icon indicating copy to clipboard operation
koa-websocket copied to clipboard

Allowing additional hooks to server on connection

Open jethrokuan opened this issue 9 years ago • 3 comments

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.

jethrokuan avatar Dec 08 '16 06:12 jethrokuan

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

skomarfaruque avatar Jan 18 '18 10:01 skomarfaruque

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.");
    });
});

kentnek avatar Apr 12 '18 17:04 kentnek

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.

david-cannady avatar May 17 '18 20:05 david-cannady