前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SSE eventSource简介

SSE eventSource简介

作者头像
frontoldman
发布2019-09-02 16:55:33
1.3K0
发布2019-09-02 16:55:33
举报
文章被收录于专栏:樯橹代码樯橹代码

eventSource简单介绍

eventSource是用来解决web上服务器端向客户端推送消息的问题的。不同于ajax轮询的复杂和websocket的资源占用过大,eventSource(sse)是一个轻量级的,易使用的消息推送api

如何使用

客户端代码

代码语言:javascript
复制
<!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代码

服务端这几种实现使用其一就可以了

代码语言:javascript
复制
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代码

代码语言:javascript
复制
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 代码

代码语言:javascript
复制
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)
    })
}

使用起来没什么问题,都可以正常运行,不过在多个客户端访问的时候,一个客户端连上之后,其他客户端就没有推送了,不知道为甚么?

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • eventSource简单介绍
  • 如何使用
    • 客户端代码
      • 服务端nodejs代码
        • 服务端expressjs代码
          • 服务端koajs 1.x 代码
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档