I have created my first application of Nodejs. I am using socket.io and express. I tried this tutorial: https://socket.io/get-started/chat/ and I find emit is what I might need not sure.
My application shows stock tickers, I am using API's, I have url like: https://quotes.example.com/v1/file.json/johndoe?&_token=tokenumber
All the users who open http://example.com/live page, I would like to push or emit stock tickers to this page. How do I best achieve this? I get the idea of live page needs to be a channel to which all user would subscribe and I am pushing data to it.
I have never worked on real-time apps before, all suggestions are welcomed.
Edited
Front-end code
<!doctype html>
<html>
<head>
<title>Live Stock Quotes App</title>
<style>
body { font: 26px Helvetica, Arial; font-weight:bold;}
#livequotes { text-align: center;}
</style>
</head>
<body>
<p id="livequotes"></p>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io('/channel1');
socket.on('live-quote', function(msg){
$('#livequotes').text(msg);
});
});
</script>
</body>
</html>
server-side code
var app = require('express')();
var http = require('http').Server(app);
var httpk = require('http');
var io = require('socket.io')(http);
var nsp = io.of('/channel1');
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
nsp.on('connection', function(socket){
nsp.emit('live-quote', 'Welcome User!');
//Make a http call
function test()
{
httpk.get("url-to-api", function(res) {
var body = ''; // Will contain the final response
res.on('data', function(data){
body += data;
});
res.on('end', function() {
var parsed = JSON.parse(body);
console.log(parsed.johndoe.bid_price);
return parsed.johndoe.bid_price;
});
});
}
setInterval(test,500);
socket.on('disconnect', function(){
console.log('1 user disconnected');
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Above code I have put as you suggested. Now, I wanted to do add something like:
setInterval(test,500);
function test (){
http.get("url-for-api", function(res) {
var body = ''; // Will contain the final response
res.on('data', function(data){
body += data;
});
// After the response is completed, parse it and log it to the console
res.on('end', function() {
var parsed = JSON.parse(body);
console.log(parsed.johndoe.bid_price);
data = parsed.johndoe.ask_price;
});
})
// If any error has occured, log error to console
.on('error', function(e) {
console.log("Got error: " + e.message);
});
}