<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
     a{
         text-decoration:none;
         color:#666
         
     }
     #topic_list div{
         border: 1px solid black
     }
     @media screen and (max-width: 600px) {
    .topic_list div a:before {
    content: attr(data-label);
    float: left;
    text-transform: uppercase;
    font-weight: bold;
  }
}
    </style>
</head>
<body>
    <input type="text" id="message">
    <button onclick="send()">获取</button>
    <div id="topic_list">

    </div>
    <script src="./node_modules/socket.io-client/dist/socket.io.js"></script>
    <script>
     var socket=new io('http://127.0.0.1:3000');
     socket.on('message',(msg)=>{
          var $=document.getElementById('topic_list')   
          var ms=JSON.parse(msg)
           ms.forEach(element => {
               var newElement=document.createElement('div');
               newElement.innerHTML=element
               var url=newElement.children[0].getAttribute('href')
               url="http://cnodejs.org"+url
               newElement.children[0].setAttribute('href',url)
               newElement.children[0].innerHTML=newElement.children[0].getAttribute('title')
               $.appendChild(newElement)
           });
     });
    
     function send(){
         var txt=document.getElementById('message').value
         console.log(txt)
         socket.emit('message',txt)
     }
    </script>
</body>
</html>

后端

var superagent=require('superagent')
var socket=require('socket.io')
var cheerio=require('cheerio')
var http=require('http').Server()
var io=socket(http)
var cnode="http://cnodejs.org"
var topics=[]
superagent.get(cnode,function(err,res){
    if(err)throw err
     Aurl=res.text.match(/<a\s.*>/gi)
     Aurl.forEach(element => {
         if(element.indexOf('topic_title')>0)topics.push(element)
     });
    io.on('connection',function(socket){
    socket.on('message',function(msg){
        console.log(msg)
        socket.emit('message',JSON.stringify(topics))
    })
})
})
 
 

http.listen(3000,function(){
    console.log("3000")
})

使用cheerio可以更简便

效果如下:

  superagent+socket.io实现前后端通信抓取cnode的文章

使用socket和ajax的区别:

ajax是无状态连接,更新数据需要不停的向后端请求,而socket是后端有更新就直接发送给前端

相关文章:

  • 2022-12-23
  • 2021-08-29
  • 2021-07-29
  • 2021-07-10
  • 2022-01-05
  • 2022-12-23
  • 2021-05-17
  • 2023-02-19
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-02
  • 2022-12-23
  • 2022-12-23
  • 2021-05-04
  • 2021-09-22
相关资源
相似解决方案