UNPKG

674 BJavaScriptView Raw
1import koa from 'koa';
2import route from 'koa-route';
3import websockify from 'koa-websocket';
4
5const app = websockify(koa());
6
7// Note it's app.ws.use and not app.use
8app.ws.use(route.all('/test/:id', function* (next) {
9 // `this` is the regular koa context created from the `ws` onConnection `socket.upgradeReq` object.
10 // the websocket is added to the context on `this.websocket`.
11 this.websocket.send('Hello World');
12 this.websocket.on('message', function(message) {
13 // do something with the message from client
14 console.log(message);
15 });
16 // yielding `next` will pass the context (this) on to the next ws middleware
17 yield next;
18}));
19
20
21app.listen(3000);