sse协议与服务器推送的小疑问?

Sse 协议

 

最近在一个小项目里面用到了sse协议(服务器推送事件Server-sent Events),记录下方便自己也方便他人,额,我知道上面是一段废话。。。

1、Web即时通讯用什么

先说下自己,自己以前怎么做的呢?用Ajax一直请求服务器,发送和获得数据。我知道这样开销很大,效率很低,可是自己太懒了,没有去做更深的研究。那么我们来看下sse的一个简单示例,这个跳跃性有点大哦。

列子:客户端

 

var source = new EventSource('url');

   

source.onmessage=function(event)

  {

   console.log(event.data)

  document.getElementById("show").innerHTML+=event.data + "<br />";

  };

 

 

服务端:

 

<?php

header('Content-Type: text/event-stream');

header('Cache-Control: no-cache');

$time = date('r');

echo "data: The server time is: {$time}\n\n";

echo "data:dd\n\n";

flush();

?>

 

 

   这样在客户端就会默认每隔3(可以自己改在结束符号\n\n之前,echo "retry:自己定义时间\n";)得到服务器的新数据,作为一个小白,看了下浏览器的请求,在浏览器端就是每隔3秒发送服务器端的请求,得到新数据,那特喵的跟我自己Ajax去有什么!!区别? 

 

如下

这是ajax轮询问发送的请求头

 

GET /test/php/test.php HTTP/1.1

Host: 127.0.0.1

Connection: keep-alive

Cache-Control: max-age=0

Accept: */*

X-Requested-With: XMLHttpRequest

User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36

Referer: http://127.0.0.1/test/index.html

Accept-Encoding: gzip, deflate, sdch

Accept-Language: zh-CN,zh;q=0.8

 

 

如下,这是sse每次发送的请求头

GET /test/php/test.php HTTP/1.1

Host: 127.0.0.1

Connection: keep-alive

Accept: text/event-stream

Cache-Control: no-cache

User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36

Referer: http://127.0.0.1/test/index.html

Accept-Encoding: gzip, deflate, sdch

Accept-Language: zh-CN,zh;q=0.8

 

 

两个在每次资源消耗上面,有什么区别?就是说,我用sse到底优势在哪里?不用自己写定时器自己每次轮询?

 

而且每次都会触发onerror 事件,我感觉现在这么用,是每次都会关闭连接,然后重新连接

 

 

 

服务器端这么写,不会每次都连接,最多超时后连接,那么这个跟常规的长轮询有虾米区别?

while(true){

 $time = date('r');

    echo "data: The server time is: {$time}\n";

    echo "retry:1000\n";

    echo "\n\n";

    @ob_flush();@flush();

    sleep(3);

} 

 

 

 

原生实现的时候,比如超过服务器30s就会报错,可能这个时候需要自己处理异常,并重新连接,然而sse里面可能是不是相当于给你封装好了。本质上就是一种长连接???????麻烦请不吝赐教

posted on 2016-09-17 19:12  橙子cookie  阅读(993)  评论(0)    收藏  举报

导航