koa-websocket
This is for Koa 1, if you're looking for Koa/Koa-route 2 compatibility see the next
branch.
Installation
npm install koa-websocket
Usage
Server:
const koa = require('koa'),
route = require('koa-route'),
websockify = require('koa-websocket');
const app = websockify(koa());
app.ws.use(route.all('/', function* (next) {
this.websocket.on('message', function(message) {
console.log(message);
});
this.websocket.send('Hello Client!');
yield next;
}));
app.listen(3000);
Client:
Here is a simple client using the WebSockets API, which is built-in to the browser. (Make sure you check that your browser version supports it.)
const socket = new WebSocket('ws://localhost:3000/');
socket.onopen = function (event) {
socket.send('Hello server!');
};
socket.onmessage = function (event) {
console.log(event.data);
};
Sharing middleware between Koa and WebSockets
To use middleware in WebSockets, the middleware must be passed in to app.ws.use()
. Passing your middleware only to app.use()
will not make it available in WebSockets. You can share your middleware between Koa and WebSockets by passing an instance of the middleware to both app.use()
and app.ws.use()
.
The following example shows how to share a session store with WebSockets.
Example: Sharing a session store
const koa = require('koa'),
route = require('koa-route'),
session = require('koa-session'),
websockify = require('koa-websocket');
const app = websockify(koa());
var sessionStore = session(app);
app.use(sessionStore);
app.ws.use(sessionStore);
app.ws.use(route.all('/', function* (next) {
console.log(this.session);
yield next;
}));
app.listen(3000);