1 | import koa from 'koa';
|
2 | import route from 'koa-route';
|
3 | import websockify from 'koa-websocket';
|
4 |
|
5 | const app = websockify(koa());
|
6 |
|
7 | // Note it's app.ws.use and not app.use
|
8 | app.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 |
|
21 | app.listen(3000);
|