SSE eventSource简介

eventSource简朴引见

eventSource是用来处理web上服务器端向客户端推送音讯的题目的。不同于ajax轮询的庞杂和websocket的资本占用过大,eventSource(sse)是一个轻量级的,易运用的音讯推送api

怎样运用

客户端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script type="text/javascript">
        (function() {
            var source = new EventSource('/stream')
            source.onopen = function(event) {
                console.log(event)
            }

            source.onmessage = function(event) {
                console.log(event)
            }

            source.onerror = function(error) {
                console.log(error)
            }
        })()
    </script>
</body>
</html>

代码很简朴,实例化api,监听事宜

服务端nodejs代码

服务端这几种完成运用其一就能够了

var http = require("http")
var fs = require('fs')

http.createServer(function (req, res) {

    var fileName = "." + req.url;

    if (fileName === "./stream") {
        res.writeHead(200, {
            "Content-Type":"text/event-stream", 
            "Cache-Control":"no-cache", 
            "Connection":"keep-alive"
        });

        res.write("retry: 10000\n");
        res.write("event: connecttime\n");
        res.write("data: " + (new Date()) + "\n\n");
        res.write("data: " + (new Date()) + "\n\n");

        interval = setInterval(function() {
            res.write("data: " + (new Date()) + "\n\n");
        }, 1000);

        req.connection.addListener("close", function () {
            clearInterval(interval);
        }, false);
  } else {
      fs.readFile('./index.html', 'utf8',function(err, html) {
          if (err) {
              console.log(err)
              return
          }
          res.end(html)
      })

  }
}).listen(9999);

服务端expressjs代码

var express = require('express')
var fs = require('fs')
var app = express()

app.get('/stream', function(req, res) {
    console.log(111)

    res.writeHead(200, {
        "Content-Type":"text/event-stream", 
        "Cache-Control":"no-cache", 
        "Connection":"keep-alive"
    });

    res.write("retry: 10000\n");
    res.write("event: connecttime\n");
    res.write("data: " + (new Date()) + "\n\n");
    res.write("data: " + (new Date()) + "\n\n");

    interval = setInterval(function() {
        res.write("data: " + (new Date()) + "\n\n");
    }, 1000);

    req.connection.addListener("close", function () {
        clearInterval(interval);
    }, false);
})

app.use(function(req, res) {
    fs.readFile('./index.html', 'utf8',function(err, html) {
        if (err) {
            console.log(err)
            return
        }
        res.send(html)
    })
})

app.listen(9999, function(err) {
    if (err) {
        console.log(err)
        return
    }
    console.log('listening on port 9999')
})

服务端koajs 1.x 代码

var koa = require('koa')
var fs = require('fs')
var PassThrough = require('stream').PassThrough

var app = koa()

app.use(function *() {
    var url = this.req.url
    if (url === '/stream') {
        var stream = new PassThrough()

        setInterval(function() {
            stream.write("data: " + (new Date()) + "\n\n")
        }, 1000);

        this.type = 'text/event-stream'
        this.body = stream
    } else {
        var html = yield koaFs
        this.body = html
    }
})

app.listen(9999, function(err) {
    if (err) {
        console.log(err)
        return 
    }
    console.log('listening on port 9999')
})

function koaFs(fn) {
    fs.readFile('./index.html', 'utf8', function(err, html) {
        fn(err, html)
    })
}

运用起来没什么题目,都可以一般运转,不过在多个客户端接见的时刻,一个客户端连上以后,其他客户端就没有推送了,不知道为甚么?

    原文作者:frontoldman
    原文地址: https://segmentfault.com/a/1190000009276347
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞