SSE eventSource簡介

eventSource簡單介紹

eventSource是用來解決web上服務器端向客戶端推送消息的問題的。不一樣於ajax輪詢的複雜和websocket的資源佔用過大,eventSource(sse)是一個輕量級的,易使用的消息推送apijavascript

如何使用

客戶端代碼

<!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,監聽事件html

服務端nodejs代碼

服務端這幾種實現使用其一就能夠了java

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)
    })
}

使用起來沒什麼問題,均可以正常運行,不過在多個客戶端訪問的時候,一個客戶端連上以後,其餘客戶端就沒有推送了,不知道爲甚麼?node

相關文章
相關標籤/搜索