koa-websocket
Koa v2 is now the default. For Koa v1 support install with koa-websocket@2 and see the legacy
branch.
Supports ws://
and wss://
Installation
npm install koa-websocket
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);
Example with Let's Encrypt (the Greenlock package):
const Koa = require('koa');
const greenlock = require('greenlock-express');
const websockify = require('koa-websocket');
const le = greenlock.create({
});
const app = websockify(new Koa(), wsOptions, le.httpsOptions);
app.ws.use((ctx) => {
ctx.websocket.on('message', function(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('/', (ctx) => {
ctx.websocket.on('message', function(message) {
console.log(message);
});
}));
app.listen(3000);
API
websockify(KoaApp, [WebSocketOptions], [httpsOptions])
The WebSocket options object just get passed right through to the new WebSocketServer(options)
call.
The optional HTTPS options object gets passed right into https.createServer(options)
. If the HTTPS options are
passed in, koa-websocket will use the built-in Node HTTPS server to provide support for the wss://
protocol.
License
MIT