UNPKG

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