0

I have a node js ( supported by express js ) http application. So I had a server.js file as follows(not there complete code).

var app = require('./app/app');
var server = http.createServer(app);
server.listen(port, host);
server.on('error', onError);
server.on('listening', onListening);

I later added websocket server to there. So it is like this now.

// app server
var app = require('./app/app');
var server = http.createServer(app);
server.listen(port, host);
server.on('error', onError);
server.on('listening', onListening);
/**
 * websocker Server
 */
var WebSocket = require('ws');
var wsServer = http.createServer();
var url = require('url');
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ server: wsServer });
var express = require('express');
var wsApp = express();
var port = 1337;

wsApp.use(function (req, res) {
    res.send({ msg: 'hello' });
});

wss.on('connection', function connection(ws) {
    console.log((new Date()) + ' Connection from origin ');

    ws.on('message', function incoming(message) {
        console.log('received: %s', message);
        var json = JSON.stringify({ type:'message', data: {hello : 'hello'} });
        ws.send(json);
    });

    var json = JSON.stringify({ type:'message', data: {hello : 'hello'} });
    ws.send(json);
});

wsServer.on('request', wsApp);
wsServer.listen(port, function () { console.log('Ws server Listening on ' + wsServer.address().port); });

Now these two are working happily. What I want is on a POST call to the http server, I want to trigger the web socket server to broadcast something to all clients. My problem is How I can trigger websocket server from http server? Routes of http server is defined in app.js file. from there how can I call websocker server function?

2 Answers 2

2

If you encapsulate your ws functionality in one single javascript file (e.g: websocket.js) you could export your websocket object as a module.

module.exports = wss;

and then require it in your http controller

var wss = require(websocket.js)

In this case it should be easy to use wss.send({...}) wherever you like.

Sign up to request clarification or add additional context in comments.

Comments

0

This peace of code is working to me:

//websocket.js
'use strict';

var io = require('socket.io');
var callme;

function Websocket(server) {

    var server = io(server);

    server.on('connection', function(socket){
        console.log('Do something here');

    });

    callme = function (val) {
        //you my choose a specific cliente if you want, read the socket.io doc
        server.emit('I may emit it ' + val);
        console.log("Called " + val);
        return 'Somebody got it';
    }

}

Websocket.route = function(req, res, next) {
        if(typeof callme == 'function'){
            res.send(callme(req.param('t')));
        }else{
            res.send('Websocket server is not running');
        }

    };

module.exports = Websocket;

On the express app definition, I put

var Websocket = require('./websocket');
app.use('/blablabla', Websocket.route);

Then, on the server js file, which run the application, I put

var server = http.createServer(app);
var s = new Websocket(server);

This last line works like the tradicional io(server); would work.

After that, when you request the address /blablabla the route will execute your websocket method.

My solution is not in production yet, let me know if somebody got an error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.