koa-websocket
Koa v2 is now the default. For Koa v1 support install with koa-websocket@2 and see the legacy
branch.
Installation
npm install koa-websocket@next
Usage
const Koa = require('koa'),
route = require('koa-route'),
websockify = require('koa-websocket');
const app = websockify(new Koa());
app.ws.use(function(ctx, next) {
return next(ctx);
});
app.ws.use(route.all('/test/:id', function (ctx) {
ctx.websocket.send('Hello World');
ctx.websocket.on('message', function(message) {
console.log(message);
});
}));
app.listen(3000);
With custom websocket options.
const Koa = require('koa'),
route = require('koa-route'),
websockify = require('koa-websocket');
const wsOptions = {};
const app = websockify(new Koa(), wsOptions);
app.ws.use(route.all('/', function* (ctx) {
// the websocket is added to the context as `this.websocket`.
ctx.websocket.on('message', function(message) {
// print message from the client
console.log(message);
});
}));
app.listen(3000);