I have an app.js which is used to trigger two events when some POST data are received:
- Insert POST data into a database
- Send a message to a client using a WebSocket
Here is the app.js (only the important lines)
var express = require('express');
var bodyParser = require('body-parser');
var server = require('./server');
var app = express();
var port = process.env.PORT || 3000;
app.post('/server', server);
app.listen(port, function(){
console.log('Slack bot listening');
});
And here is the server.js (only the important lines)
var db = require('./DB');
var WebSocketServer = require('ws').Server;
var insertData = function(req, res){
var wss = new WebSocketServer({server: server});
console.log('WebSocketServer created');
wss.on('connection', function(wss){
wss.send(JSON.stringify('Socket open'));
});
wss.on('close', function(){
console.log('WebServerSocket has been closed');
});
};
module.exports = insertData;
What I would like to achieve is to set the WebSocketServer in a way that it listen to the same port of the app. I thought about passing the server var from app.js to server.js but
- I think this a not an elegant way to do it
- I don't know how to do it
What do you guys think?
from Express and WebSocket listening on the same port
No comments:
Post a Comment