Code Monkey home page Code Monkey logo

express-ws-routes's Introduction

express-ws-routes

Handle WebSocket connections using ws via express routes.

Differences from express-ws:

  • Does not prefix the request URL with '.websocket' and instead uses a fake WEBSOCKET HTTP method
  • Websocket requests must be explicitly accepted (see ws's verifyClient option)
  • Websocket requests can be rejected or the route can pass control to the next handler using next() (just like express routes)
  • Supports detached routers (i.e. express.Router())

Installation

If using NPM v3, install express v4.5.0 or later: npm install express@^4.5.0

npm install express-ws-routes

Usage

Express routes are used to verify and handle socket connections.

var express = require('express');

// Create an express app with websocket support
var app = require('express-ws-routes')();

// Add routes directly to the app... 
app.websocket('/myurl', function(info, cb, next) {
	// `info` is the same as ws's verifyClient
	console.log(
		'ws req from %s using origin %s',
		info.req.originalUrl || info.req.url,
		info.origin
	);

	// Accept connections by passing a function to cb that will handle the connected websocket
	cb(function(socket) {
		socket.send('connected!');
	});
});

// ... or to detached routers
var router = express.Router();
router.websocket('/sub/path', function(info, cb, next) {
	cb(function(socket) {
		socket.send('connected!');
	});
});
app.use('/attachment/path', router);

// Reject requests using cb just like you would with ws's verifyClient
app.websocket('/bad/path', function(info, cb, next) {
	cb(false);
	
	// Using the optional arguments...
	//cb(false, 401);
	//cb(false, 401, 'No access!');
});

// Skip handlers by calling next(), just like normal routes
app.websocket('/skipped', function(info, cb, next) {
	console.log('Skipped!');
	next();
});

// Using app.listen will also create a require('ws').Server
var server = app.listen(8080, function() {
	console.log('Server listening on port 8080...');
});

// The WebSocket server instance is available as a property of the HTTP server
server.wsServer.on('connection', function(socket) {
	console.log('connection to %s', socket.upgradeReq.url);
});

Options

Module Name for 'express'

By default the express module name is express but can be changed:

// Extend express using a specific module name, instead of 'express'
var app = require('express-ws-routes')({
	moduleName: 'my-custom-express' // i.e. require('my-custom-express')
});

Fake HTTP Method

By default the fake HTTP method is WEBSOCKET but can be changed:

// Use a different web socket
var app = require('express-ws-routes')({
	methodName: 'WS'
});

// Note: Method for attaching handlers will always be lowercase
app.ws(function(info, cb, next) {
	// ...
});

Manual Setup

Instead of using the helper method you can do the following:

var options = {}; // See 'Options' above
var expressWs = require('express-ws-routes');
var app = expressWs.extendExpress(options)();

var server = http.createServer(app);
server.wsServer = expressWs.createWebSocketServer(server, app, options);
server.listen(8080, function() {
	console.log('Server listening on port 8080...');
});

License

The MIT License (MIT)

Copyright (c) 2015 Andre Mekkawi <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

express-ws-routes's People

Contributors

amekkawi avatar

Stargazers

ɐʇɯon3ɹ avatar みづな れい avatar Islomkhodja Hamidullakhodjaev avatar Davlatjon Shavkatov avatar Jimmy Huang avatar Lezsák Domonkos avatar Axel Rindle avatar  avatar wannyk avatar telkomops avatar Pavel Zinovev avatar  avatar vi-dot avatar  avatar  avatar Che-Wei Lin avatar  avatar Prashanth Chandra avatar Christopher Ritsen avatar Ron Korving avatar

Watchers

James Cloos avatar  avatar  avatar Lezsák Domonkos avatar  avatar

express-ws-routes's Issues

Detached Routers example throwing error TypeError: Cannot call method 'push' of undefined on line 77 of express-ws-routes.js

First of all thanks a lot for writing this library which supports express detached routing.

I am trying to put it to use and running into an issue. My application is running on NodeJS 0.10.35 with Express 4 and above.

I am importing the express-ws-routes module in my code as shown below

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

Then I am trying to add your example in the code

var router = express.Router();

    router.websocket('/sub/path', function(info, cb, next) {
      cb(function(socket) {
        console.info('came here');
        socket.send('connected!');
      });
    });

Rest of my router code is like this

router.post('/submitReport', isLoggedIn, reportsRoute.submitReport);
router.get('/getProductList', searchRoute.getProductList);

When i include the example my server crashes and throws TypeError: Cannot call method 'push' of undefined on line 77 of express-ws-routes.js.

What could I be doing wrong here, could you please help..?

Regards,
Narendra

The code does not work anymore.

Modifying Express underlying routers seems to be a good idea. But the code itself does not work any more.

steps to reproduce the problem

(1) depenancies

  1. express version 4.16.3
  2. express-ws-route 1.1.0
  3. ws 5.1.1

(2) actual output after the server set up and accepts websocket connection from /sim_world

 express:router dispatching WEBSOCKET /sim_world +33s
  express:router query  : /sim_world +1ms
  express:router expressInit  : /sim_world +0ms
  express:router urlencodedParser  : /sim_world +0ms
  express:router jsonParser  : /sim_world +0ms
  express:router methodOverride  : /sim_world +0ms
  express:router logger  : /sim_world +1ms
  express:router corsMiddleware  : /sim_world +0ms
  express:router serveStatic  : /sim_world +0ms
  express:router <anonymous>  : /sim_world +0ms
  express:router <anonymous>  : /sim_world +0ms
  express:view lookup "error.jade" +1ms
  express:view stat "/Users/lei.wang1/Github/RandomMapGenerator/backend/bin/views/error.jade" +0ms
  express:view render "/Users/lei.wang1/Github/RandomMapGenerator/backend/bin/views/error.jade" +0ms

(3) websocket method

app.websocket('/sim_world', function(info, cb ,next){
	cb(function(socket){
		socket.send('connected')

		socket.on('message', function incomingMessage(message){
			socket.send("Thank you very much!")
		})

	})

})

I am suspecting that the registration of the method in Application and Router failed because of this

Incompatible with express-session when using named route parameters

Code:

app.websocket('/substitue/:a/:b', (info, cb) => cb(socket => socket.on('message',
    message => socket.send(message.replace(info.req.params.a, info.req.params.b)))));

Requested URL:

ws://localhost:3000/substitue

(Please note that ws://localhost:3000/substitue/x/y works well)

Result:

Server crash

Output:

_http_outgoing.js:236
      this.outputSize += header.length;
                                ^

TypeError: Cannot read property 'length' of null
    at ServerResponse._send (_http_outgoing.js:236:33)
    at write_ (_http_outgoing.js:674:15)
    at ServerResponse.end (_http_outgoing.js:760:5)
    at writeend (/home/led/Dokumentumok/gg/projects/setup-server/node_modules/express-session/index.js:261:22)
    at Immediate.onsave (/home/led/Dokumentumok/gg/projects/setup-server/node_modules/express-session/index.js:335:11)
    at runCallback (timers.js:763:18)
    at tryOnImmediate (timers.js:734:5)
    at processImmediate (timers.js:716:5)

Process finished with exit code 1

Environment:

uname -a Linux ledomi-pc 4.12.5-gentoo #2 SMP Thu Mar 29 11:47:00 CEST 2018 x86_64 Intel(R) Core(TM)2 Duo CPU E7500 @ 2.93GHz GenuineIntel GNU/Linux
node --version v9.9.0
Used middlewares morgan (logger), express.json, express.urlencoded({extended: false}), stylus, some static paths, express-session, passport (initialize and session)

TypeError: router.websocket is not a function

I am unable to add another route to my existing express app I changed my app.js to include following code

var express = require('express');
...
var wstest = require('./routes/tracingtest');
...
//var app = express();
var app = require('express-ws-routes')();
...
app.use('/wstest', wstest);

and my route file tracingtest.js looks like

var express = require('express');
var router = express.Router();

router.websocket('/', function(info, cb, next) {
    cb(function(socket) {
        socket.send('connected!');
    });
});

But when I Start the app I get this Error

/home/ehsan/n_ode/trace_student/routes/tracingtest.js:4
router.websocket('/', function(info, cb, next) {
       ^
TypeError: router.websocket is not a function
    at Object.<anonymous> (/home/ehsan/n_ode/trace_student/routes/tracingtest.js:4:8)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:313:12)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at Object.<anonymous> (/home/ehsan/n_ode/trace_student/app.js:13:14)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:313:12)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at Object.<anonymous> (/home/ehsan/n_ode/trace_student/bin/www:7:11)
    at Module._compile (module.js:435:26)

how to get the clients msg

app.ws('/ws/chat/:uid', function(info, cb, next) {
// info is the same as ws's verifyClient
console.log(
'ws req from %s using origin %s',
info.req.originalUrl || info.req.url,
info.origin
);
console.log(info.req.params.uid);
//console.log(info.req.socket.server.verifyClient);
// Accept connections by passing a function to cb that will handle the connected websocket
cb(function(socket) {
console.log(socket.route.stack);
socket.send(info.req.params.uid);
});
});

Breaks app.set() call from original express?

When loading this and replacing my existing app = express(), I'm now getting an error that app.set is not a function. How can I use this with the default usage of epxress()?

let app = require('express-ws-routes'),
	// app = express(),
	secret = '$eCuRiTy',
	sessionStore = new mongodbSession({
		uri: `mongodb://${config.server}/squarrels_sessions`,
		collection: 'sessions'
	});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
// app.use(cookieParser(secret));

this.ee.on is not a function

Hi I'm trying to use your module and getting the above error. The client makes a successful connection but then I see this error.

{"error":{},"level":"error","message":"uncaughtException: this.ee.on is not a function\nTypeError: this.ee.on is not a function\n at Ultron.on (/Users/roblingstuyl/_sandbox/mouth/node_modules/ultron/index.js:42:11)\n at firstHandler (/Users/roblingstuyl/_sandbox/mouth/node_modules/express-ws-routes/node_modules/ws/lib/WebSocket.js:812:12)\n at _combinedTickCallback (internal/process/next_tick.js:131:7)\n at process._tickCallback (internal/process/next_tick.js:180:9)","stack":"TypeError: this.ee.on is not a function\n at Ultron.on (/Users/roblingstuyl/_sandbox/mouth/node_modules/ultron/index.js:42:11)\n at firstHandler (/Users/roblingstuyl/_sandbox/mouth/node_modules/express-ws-routes/node_modules/ws/lib/WebSocket.js:812:12)\n at _combinedTickCallback (internal/process/next_tick.js:131:7)\n at process._tickCallback (internal/process/next_tick.js:180:9)","exception":true,"date":"Tue Oct 02 2018 15:38:39 GMT-0600 (MDT)","process":{"pid":14890,"uid":501,"gid":20,"cwd":"/Users/roblingstuyl/_sandbox/mouth","execPath":"/usr/local/Cellar/node/8.7.0/bin/node","version":"v8.7.0","argv":["/usr/local/Cellar/node/8.7.0/bin/node","/Users/roblingstuyl/_sandbox/mouth/server.js"],"memoryUsage":{"rss":88690688,"heapTotal":69128192,"heapUsed":51200392,"external":18955114}},"os":{"loadavg":[2.19775390625,2.29541015625,2.25927734375],"uptime":105227},"trace":[{"column":11,"file":"/Users/roblingstuyl/_sandbox/mouth/node_modules/ultron/index.js","function":"Ultron.on","line":42,"method":"on","native":false},{"column":12,"file":"/Users/roblingstuyl/_sandbox/mouth/node_modules/express-ws-routes/node_modules/ws/lib/WebSocket.js","function":"firstHandler","line":812,"method":null,"native":false},{"column":7,"file":"internal/process/next_tick.js","function":"_combinedTickCallback","line":131,"method":null,"native":false},{"column":9,"file":"internal/process/next_tick.js","function":"process._tickCallback","line":180,"method":"_tickCallback","native":false}]}

This is my code

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json({ type: 'application/*+json'});
router.use(bodyParser.urlencoded({ extended: true }));

router.post('/', function (req, res) {
...
});

router.websocket('/', function(info, cb, next) {
  logger.info( `ws req from ${info.req.originalUrl || info.req.url} using origin ${info.origin}` );

  // Accept connections by passing a function to cb that will handle the connected websocket
  cb(function(socket,value) {
    console.log(value);
    socket.on('message', function(msg) {
      console.log(msg);
      socket.send(JSON.stringify({'orig':msg}));
    });
  });
});

module.exports = router;

how to get message??

express-ws-routes modules Send message to "cb(function(socket)”

but i don’t no receive message by websocket.

how to get a message??

Question: How to Send to Specific Routes?

I'm using ws for my websocket communication. The receiving part is like in a usual express REST api. But I don't understand the sending part.

So if this server A who want to send:

createServer: (options)->
   @.wss = new WebSocketServer({ port: process.env.PORT_WEBSOCKET})
   self = @
   logger.info("Websocket listening on #{process.env.PORT_WEBSOCKET}")
   ...

   @.wss.on 'connection', (ws) ->
       ....


send: (data)->
   @.ws.send JSON.stringify data

And this is server B who listens:

module.exports = (app)->
  app.websocket('/routeX', (info, cb, next) ->
    console.log(
      'ws req from %s using origin %s',
      info.req.originalUrl || info.req.url,
      info.origin
    )

Do I need an own connection for each route?
ws1 = new WebSocket("ws://.../routeX")
ws2 = new WebSocket("ws://.../routeY")
ws3 = new WebSocket("ws://.../routeZ")

Or can server A specify the route and just connect to a more common endpoint? And how would this be done?
ws = new WebSocket("ws://myincredibleapi.com:7000")

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.