WebSocket
是什么: WebSocket是一種通訊手段,基于TCP協(xié)議,默認(rèn)端口也是80和443,協(xié)議標(biāo)識(shí)符是ws(加密為wss),它實(shí)現(xiàn)了瀏覽器與服務(wù)器的全雙工通信,擴(kuò)展了瀏覽器與服務(wù)端的通信功能,使服務(wù)端也能主動(dòng)向客戶端發(fā)送數(shù)據(jù),不受跨域的限制。
有什么用: WebSocket用來(lái)解決http不能持久連接的問(wèn)題,因?yàn)榭梢噪p向通信所以可以用來(lái)實(shí)現(xiàn)聊天室,以及其他由服務(wù)端主動(dòng)推送的功能例如 實(shí)時(shí)天氣、股票報(bào)價(jià)、余票顯示、消息通知等。
EventSource
是什么: EventSource的官方名稱(chēng)應(yīng)該是 Server-sent events(縮寫(xiě)SSE)服務(wù)端派發(fā)事件,EventSource 基于http協(xié)議只是簡(jiǎn)單的單項(xiàng)通信,實(shí)現(xiàn)了服務(wù)端推的過(guò)程客戶端無(wú)法通過(guò)EventSource向服務(wù)端發(fā)送數(shù)據(jù)。喜聞樂(lè)見(jiàn)的是ie并沒(méi)有良好的兼容當(dāng)然也有解決的辦法比如 npm install event-source-polyfill。雖然不能實(shí)現(xiàn)雙向通信但是在功能設(shè)計(jì)上他也有一些優(yōu)點(diǎn)比如可以自動(dòng)重連接,event IDs,以及發(fā)送隨機(jī)事件的能力(WebSocket要借助第三方庫(kù)比如socket.io可以實(shí)現(xiàn)重連。)
有什么用: 因?yàn)槭軉雾?xiàng)通信的限制EventSource只能用來(lái)實(shí)現(xiàn)像股票報(bào)價(jià)、新聞推送、實(shí)時(shí)天氣這些只需要服務(wù)器發(fā)送消息給客戶端場(chǎng)景中。EventSource的使用更加便捷這也是他的優(yōu)點(diǎn)。
WebSocket & EventSource 的區(qū)別
WebSocket基于TCP協(xié)議,EventSource基于http協(xié)議。
EventSource是單向通信,而websocket是雙向通信。
EventSource只能發(fā)送文本,而websocket支持發(fā)送二進(jìn)制數(shù)據(jù)。
在實(shí)現(xiàn)上EventSource比websocket更簡(jiǎn)單。
EventSource有自動(dòng)重連接(不借助第三方)以及發(fā)送隨機(jī)事件的能力。
websocket的資源占用過(guò)大EventSource更輕量。
websocket可以跨域,EventSource基于http跨域需要服務(wù)端設(shè)置請(qǐng)求頭
EventSource的實(shí)現(xiàn)案例
服務(wù)端代碼:
1:nodejs +express 基于自簽的https
//創(chuàng)建https服務(wù)
var app =require('../app');
var https =require('https');
var fs =require('fs');
var path =require('path');
const SSLPORT =443;
app.set('port', SSLPORT);
/**
* Create HTTP server.
*/
//根據(jù)項(xiàng)目的路徑導(dǎo)入生成的證書(shū)文件
const privateKey? =fs.readFileSync(path.join(__dirname, './server.key'), 'utf8');
const certificate =fs.readFileSync(path.join(__dirname, './server.crt'), 'utf8');
const credentials = {key:privateKey, cert:certificate};
const httpsServer =https.createServer(credentials, app);
//創(chuàng)建https服務(wù)器
httpsServer.listen(SSLPORT, function() {
console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT);
});
格式說(shuō)明
event-source必須編碼成utf-8的格式,消息的每個(gè)字段使用"\n"來(lái)做分割,并且需要下面4個(gè)規(guī)范定義好的字段:?
event: 事件類(lèi)型?
data: 發(fā)送的數(shù)據(jù)?
id: 每一條事件流的ID?
retry: 告知瀏覽器在所有的連接丟失之后重新開(kāi)啟新的連接等待的時(shí)間,在自動(dòng)重新連接的過(guò)程中,之前收到的最后一個(gè)事件流ID會(huì)被發(fā)送到服務(wù)端。
其中data 數(shù)據(jù)的結(jié)束符必須是‘\n\n’兩個(gè)哦。
如果沒(méi)有數(shù)據(jù)發(fā)送的時(shí)候,最好定期發(fā)送以: xxx\n\n 的注釋數(shù)據(jù) 防止與瀏覽器斷開(kāi)。
//添加routes url地址
var express =require('express');?
var router =express.Router();
/* GET home page. */
router.get('/', function (req, res, next) {
res.render('index', {title:'Express'});
});
let reqs={};
router.get('/event-stream', function (req, res, next) {
let id =req.query.id;
? ? reqs[id] = {
res:res,
? ? };
? ? res.writeHead(200, {
????????"Content-Type":"text/event-stream",
? ? ? ? "Cache-Control":"no-cache",
? ? ? ? "Connection":"keep-alive",
? ? ? ? "Access-Control-Allow-Origin":'*',
? ? });
? ? res.write("retry: 10000\n");
? ? res.write("id: "+id+"\n");
? ? req.connection.addListener("close", function () {
console.info(id);
? ? ? ? delete reqs[id]
}, false);
});
setInterval(function () {
let data = {
name:'張三',
? ? ? ? age:Math.random()*100
? ? }
console.info(Object.getOwnPropertyNames(reqs).length)
for (let id in reqs){
reqs[id].res.write("data: " + (JSON.stringify(data)) +"\n\n");
? ? }
}, 1000);
module.exports =router;
前端代碼:
如果使用vue的話需要引入第三方兼容插件
event-source-polyfill
import {NativeEventSource, EventSourcePolyfill }from 'event-source-polyfill'
let EventSource =NativeEventSource||EventSourcePolyfill
let params ='id='+Math.round(Math.random()*99999);
var source =new EventSource('https://192.168.4.15/event-stream?'+params, {withCredentials:true, format:'json' });
source.addEventListener('message', function(event) {
var data =event.data;
? console.info(data);
? // handle message
}, false);
見(jiàn)結(jié)果:
EventSource 使用場(chǎng)景一版是前端只是展示數(shù)據(jù),而有的時(shí)候因?yàn)槭莌ttps,呵呵買(mǎi)不起證書(shū)。所以自己生成了一套證書(shū)。但是websocket不支持非法證書(shū)。所以終于找到了這個(gè)玩意兒。
java 版?https://luoyuer.com/archives/springbooteventstream.html
抓包詳解請(qǐng)轉(zhuǎn)到?http://www.lxweimin.com/p/3d7b0bbf435a