@parthar/express-ws

1.0.0 • Public • Published

Express Ws

Express with Websockets

Consider this as a drop-in replacement for ExpressJS with additional functionality to handle Websockets in familiar express-middelware style.

Installation

$ npm install @parthar/express-ws --save # the package

Usage

var expressWs = require("@parthar/express-ws");
var express = require("express");

// use like normal express-apps
var appWs = expressWs();
appWs.get("/hello", function (req, res, next) {
    res.send("hello world");
});

// mix both kinds of apps
var app = express();
app.get("/express", function (req, res, next) {
    res.send("plain express");
});
appWs.use(app);

// handle websockets upgrades in express-style
// use res.upgradeWs to accept the upgrade
app.get("/ws", function (req, res, next) {
    isAuthorized(req.headers.authorization, function (err, auth) {
        if (err) {
            return res.sendStatus(500);
        }
        if (!auth) {
            return res.sendStatus(401);
        }
        res.upgradeWs(function (ws) {
            ws.on("open", function () {
                // websocket opened
            });
            ws.on("close", function () {
                // websocket closed
            });
            ...
        });
    });
});

// listen on a port; similar to http.Server.listen()
appWs.listen(8080, callback);

// close when done; closes all opened websocket-connections
appWs.close(callback);

// http & ws servers are available as attributes: appWs.httpServer & appWs.wsServer
// can use these attributes for full functionality provided by respective entities

Notes

The Websocker-server is started in "noServer" mode. Also, "clientTracking" is enabled, which means that all websocket clients are available on the server via appWs.wsServer.clients attribute. Refer to Websockets for more details.

Package Sidebar

Install

npm i @parthar/express-ws

Weekly Downloads

0

Version

1.0.0

License

ISC

Unpacked Size

6.43 kB

Total Files

4

Last publish

Collaborators

  • partharamanujam