How can I have faye-websockets code running in the browser?

726 views Asked by At

I'm new with node.js/express and all and I want to be able to notify any clients in browser about a new message received from some algorithm in the back-end. The publisher algorithm connect to the websocket and writes the message.

As far as I've looked there were examples which recommended websockets but I haven't been able to run that code in browser only in console.

Example client code:

            var WebSocket = require('faye-websocket');
            var ws  = new WebSocket.Client('ws://localhost:1234');
            var http = require('http');

            var port = process.env.PORT || 1235;

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

            // receive a message from the server
            ws.on('message', function(event) {
                alert(JSON.parse(event.data));
            });

Thank you

1

There are 1 answers

0
emmerich On

Found the answer after some trial/error iterations.

The algorithm now does a POST to an URL which in turn triggers a write to sockets for all connected clients via socket.io.

Client code:

var socket = io('http://localhost:7777');
socket.on('message', function (msg) {
    document.body.insertAdjacentHTML( 'beforeend', '<div id="myID">'+msg+'</div>' );
});

And on the server, when client connects I retain it's socket into an array so I can write to each one:

Server code:

io.on('connection', function(socket){
console.log('a user connected: '+socket.id);
var id = clientCount++;
clientSockets[id] = socket;

socket.on('disconnect', function(){
    console.log('user disconnected');
    delete clientSockets[id];
    socket = null
});

});
app.post('/alerts', function(req, res) {
req.accepts(['json', 'application']);
console.log("Algo did a POST on /alerts!");
// send the message to all clients
//console.log(req.body);
for(var i in clientSockets) {
    clientSockets[i].send(JSON.stringify(req.body));
}
res.send(200);
});

In conclusion, I'm not using faye-websockets but instead socket.io