Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Package express-ws doesn't let clients connect

I have an express router defined for express-ws npm package. The router looks is exported like:

//ws.js
var express = require('express');
var router = express.Router();

var connections = {};
router.ws('/connect/', function (ws, req) {
    // console.log(ws);
    ws.on('close', function(x, y, z) {
        console.log(a, b, c);
    });
});

module.exports = router;

The (not all) statements in the express app are (and in order):

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

var index = require('./routes/index');
var ws = require('./routes/ws');

...
...

app.use('/ws', ws);
app.use('/*', index);

The server has statements like:

//bin/www - Generated by express generator

var app = require('../app');
var debug = require('debug')('server:server');
var http = require('http');

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

var server = http.createServer(app);
server.listen(port);

After I run it, I am not able to connect to /ws route over websocket. Am I missing something here? Is there a better way to create websocket running on Express 4?

This is the error I see at the client! What am I doing wrong?

enter image description here

like image 649
Mayank Avatar asked Nov 01 '16 14:11

Mayank


1 Answers

changes to app.js

var app = express();
var server = require('http').Server(app);
var expressWs = require('express-ws')(app,server);
...
...
//module.exports = app;
module.exports = {app: app,server: server};

changes to bin/www

//var app = require('../app');
var app = require('../app').app;
...
...
//var server = http.createServer(app);
var server = require('../app').server;
like image 194
Shasankar Avatar answered Oct 02 '22 20:10

Shasankar