Intercommunication between two pages in SSE

Communication between two pages

First build the express framework, then send the data to the server through the two page, and the server transmits the data to the one page

send data in two, display in one

  • router/index.js
var axios = require('axios');

router.get('/sse_server', (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  setInterval(function () {
    console.log(message);
    if (message.length > 0) {
      var msg = message.shift();
      res.write('data:' + msg + '\n\n');
    }
  }, 1000);
})

router.get('/one', (req, res) => {
  res.render('one');
})
router.get('/two', (req, res) => {
  res.render('two');
})
router.get('/ajax', (req, res) => {
  var content = req.query.content;
  message.push(content);
  res.end('ok');
})
  • one.ejs
<!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>新消息</title>
</head>
<body>
  <h1>接受到的消息</h1>
  <script>
    var source = new EventSource('/sse_server');
    var i = 0;    
    var timer = null;
    source.onmessage = function(data){
      console.log(data.data);
      if(timer) return;
      timer = setInterval(function () {
        i++;
        if (i % 4 == 0) {
          document.title = '[   ]接受消息';
        } else if (i % 4 == 1) {
          document.title = '[新  ]接受消息';
        } else if (i % 4 == 2) {
          document.title = '[新消 ]接受消息';
        } else if (i % 4 == 3) {
          document.title = '[新消息]接受消息';
        }
      }, 500);
      
    }
    </script>
</body>
</html>
  • two.ejs
<!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>
  <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
  <input type="text">
  <button>发送</button>
  <script>
    var btn = document.querySelector('button');
    btn.onclick = function(){
      var value = $('input').val();
      $.get('/ajax',{content:value},function(res){
        console.log(res);
      })

    }
  </script>
</body>
</html>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324592825&siteId=291194637