Skip to content

WebSocket endpoints for express applications

Notifications You must be signed in to change notification settings

rndmania/express-ws

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

30 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

express-ws

WebSocket endpoints for express applications. Gives WebSocket connections access to functionality from express middlewares.

Installation

npm install express-ws

Usage

Add this line to your express application:

var expressWs = require('express-ws')(app); //app = express app

Now you will be able to add WebSocket routes (almost) the same way you add other routes. The following snippet sets up a simple echo server at /echo.

app.ws('/echo', function(ws, req) {
  ws.on('message', function(msg) {
    ws.send(msg);
  });
});

Example

var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);

app.use(function (req, res, next) {
  console.log('middleware');
  req.testing = 'testing';
  return next();
});

app.get('/', function(req, res, next){
  console.log('get route', req.testing);
  res.end();
});

app.ws('/', function(ws, req) {
  ws.on('message', function(msg) {
    console.log(msg);
  });
  console.log('socket', req.testing);
});

app.listen(3000);

About

WebSocket endpoints for express applications

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%