SSE两个页面的相互通信

两个页面之间互相通信

首先搭建express框架,然后通过two页面发送数据给服务器,服务器把数据传送给one页面

在two 中发送数据,在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>
posted @ 2018-04-19 11:55  清风白水  阅读(559)  评论(0编辑  收藏  举报