kudos/koa-websocket

example doesn't work

Opened this issue ยท 8 comments

const koa = require('koa');
const websockify = require('koa-websocket');
const router = require('koa-router');
const app = new koa();
const api = router();
const socket = websockify(app);

api.get('/*', function* (next) {
    this.websocket.send('Hello World');
    this.websocket.on('message', function(message) {
        console.log(message);
    });
});

app.ws.use(api.routes()).use(api.allowedMethods());
app.listen(3000);

When I try to debug with wscat -c ws://localhost:3000 nothing happens :(

bump

same here. i searched and saw some discussion about this. any update?

Seems this project is broken, I'm having the same issue :(

kudos commented

koa-router is not explicitly supported, but patches with tests are welcome.

This following example is working for me

const router = require('koa-router')();
const websockify = require('koa-websocket');
const Koa = require('koa');

const app = websockify(new Koa());

router.get('/ping', async (ctx) => {
  ctx.websocket.send('Hello world');
  ctx.websocket.on('message', (message) => {
    console.log(message);
    ctx.websocket.send(message);
  });
});

app.ws.use(router.routes()).use(router.allowedMethods());
app.listen(3000);

Then test with wscat:

$ wscat --connect ws://localhost:3000/ping                                                                                         *[feature/JWA-3699-user-i-want-to-have-an-api-endp] 
Connected (press CTRL+C to quit)
< Hello world
> Test
< Test
>

My package.json

  "dependencies": {
    ...
    "koa": "2.13.0",
    "koa-router": "9.4.0",
    "koa-websocket": "^6.0.0",
    ...
  }

This still works with @koa/router

Does it work with latest version though? I donโ€™t see how it suddenly works.

hahah honestly, your guess is as good as mine. Im using it right now without any issues