Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

javascript - node, socket.io - update client when new entry added to news feed?

I've created client and server of node with socket.io. server is executing 4 get requests of news feed and fetched the data. These data is sent to the client with socket.io.

client is displaying news feed on the occurrence of specific socket.io event. This works well for once. Here is the code and working fiddle

server.js

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')
  , redis = require("redis");

var http = require("http");

// initialize the container for our data
var data = "";

var nfs = [
    "http://economictimes.feedsportal.com/c/33041/f/534037/index.rss",
    "http://www.timesonline.co.uk/tol/feeds/rss/uknews.xml",
    "http://www.independent.co.uk/news/business/rss",
    "http://www.dailymail.co.uk/money/index.rss"
];

//setInterval(function() {
    for(var i=0; i<nfs.length; i++){
        //console.log(nfs[i]);  
            http.get(nfs[i], function (http_res) {

                // this event fires many times, each time collecting another piece of the response
                http_res.on("data", function (chunk) {
                    // append this chunk to our growing `data` var
                    data += chunk;
                });

                // this event fires *one* time, after all the `data` events/chunks have been gathered
                http_res.on("end", function () {
                    // you can use res.send instead of console.log to output via express
                    console.log("data received");
                });
            }); 
    }
//}, 30000);

app.listen(8080);

function handler (req, res) {
  fs.readFile(__dirname + '/client.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.on('connection', function (socket) {

  //setInterval(function() {
      socket.emit('news', data);
      /*socket.on('my other event', function (data) {
        console.log(data);
      });*/
  //}, 5000);

});

client.html

<html>
    <head>
        <script src="https://cdn.socket.io/socket.io-1.2.1.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script>
            //socket io client
            var socket = io.connect('http://localhost:8080');

            //on connetion, updates connection state and sends subscribe request
            socket.on('connect', function(data){
                setStatus('connected');
                socket.emit('subscribe', {channel:'notif'});
            });

            //when reconnection is attempted, updates status 
            socket.on('reconnecting', function(data){
                setStatus('reconnecting');
            });

            //on new message adds a new message to display

            socket.on('news', function (data) {
                console.log(data);              
                //socket.emit('my other event', { my: 'data' });
                addMessage(data);
            });

            /*socket.on('news', function (data) {
                debugger;
                socket.emit('my other event', { my: 'data' }
                var msg = "";
                if (data) {
                    msg = data; 
                }
            addMessage(msg);
            });*/

            //updates status to the status div
            function setStatus(msg) {
                $('#status').html('Connection Status : ' + msg);
            }

            //adds message to messages div
            function addMessage(msg) {  
                //debugger;
                var $xml = $(msg);
                var html = '';
                $xml.find("item").each(function() {
                    var $item = $(this);                                        
                    html += '<li>' +
                        '<h3><a href ="' + $item.find("link").text() + '" target="_new">' +
                        $item.find("title").text() + '</a></h3> ' +
                        '<p>' + $item.find("description").text() + '</p>' +
                        // '<p>' + $item.attr("c:date") + '</p>' +
                        '</li>';                    
                });             
                $('#result').prepend(html);
}
        </script>
    </head>
    <body>
        <div id="status"></div><br><br>     
        <ul id="result"></ul>       
    </body>
</html>

What I understand about socket.io is that we don't need long server polling and so how do server come to know that news is added to the respected news feed.

How do I update the client with newly added news when news is added to the news feed rss ???

Update Ok so from all the responses I get the point that it is not possible for socket.io to know that new entry has been added. So, how do I know (which tools/libraries do require to know that new entry has beed added and update the client as well) ???

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Retrieving the messages from the news feeds are completely independent of socket.io unless the news feeds implement sockets on their end and your server becomes their client. So you will have to continue to poll them with http requests to know whether they have updated data.

In order to notify your clients of the update you would just emit the news event. Presumably you would have logic on the server to make sure you are only sending events which have not previously be sent.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...