UNPKG

884 BMarkdownView Raw
1# koa-websocket
2
3[![Circle CI](https://circleci.com/gh/kudos/koa-websocket.svg?style=svg)](https://circleci.com/gh/kudos/koa-websocket)
4
5## Installation
6
7`npm install koa-websocket`
8
9## Usage
10
11```js
12const koa = require('koa'),
13 route = require('koa-route'),
14 websockify = require('koa-websocket');
15
16const app = websockify(koa());
17
18// Note it's app.ws.use and not app.use
19app.ws.use(route.all('/test/:id', function* (next) {
20 // `this` is the regular koa context created from the `ws` onConnection `socket.upgradeReq` object.
21 // the websocket is added to the context on `this.websocket`.
22 this.websocket.send('Hello World');
23 this.websocket.on('message', function(message) {
24 // do something with the message from client
25 console.log(message);
26 });
27 // yielding `next` will pass the context (this) on to the next ws middleware
28 yield next;
29}));
30
31app.listen(3000);
32
33```