koa-websocket
Light wrapper around Koa providing a websocket middleware handler that is koa-route compatible.
Last updated 6 months ago by kudos .
MIT · Repository · Bugs · Original npm · Tarball
$ cnpm install koa-websocket 
SYNC missed versions from official npm registry.

koa-websocket

Circle CI

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());

// Regular middleware
// Note it's app.ws.use and not app.use
app.ws.use(function(ctx, next) {
  // return `next` to pass the context (ctx) on to the next ws middleware
  return next(ctx);
});

// Using routes
app.ws.use(route.all('/test/:id', function (ctx) {
  // `ctx` is the regular koa context created from the `ws` onConnection `socket.upgradeReq` object.
  // the websocket is added to the context on `ctx.websocket`.
  ctx.websocket.send('Hello World');
  ctx.websocket.on('message', function(message) {
    // do something with the message from client
        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);

Maintainers (1)
Downloads
Today 2
This Week 76
This Month 1,123
Last Day 74
Last Week 492
Last Month 1,791
Dependencies (4)
Dev Dependencies (3)

Copyright 2014 - 2016 © taobao.org |