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


i'm new node.js/express , , want able notify clients in browser new message received algorithm in back-end. publisher algorithm connect websocket , writes message.

as far i've looked there examples recommended websockets haven't been able run code in browser 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 message server             ws.on('message', function(event) {                 alert(json.parse(event.data));             }); 

thank you

found answer after trial/error iterations.

the algorithm post url in turn triggers write sockets 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 server, when client connects retain it's socket array can write 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 post on /alerts!"); // send message clients //console.log(req.body); for(var in clientsockets) {     clientsockets[i].send(json.stringify(req.body)); } res.send(200); }); 

in conclusion, i'm not using faye-websockets instead socket.io


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -