WebSocket
是什么: WebSocket是一種通訊手段,基于TCP協議,默認端口也是80和443,協議標識符是ws(加密為wss),它實現了瀏覽器與服務器的全雙工通信,擴展了瀏覽器與服務端的通信功能,使服務端也能主動向客戶端發送數據,不受跨域的限制。
有什么用: WebSocket用來解決http不能持久連接的問題,因為可以雙向通信所以可以用來實現聊天室,以及其他由服務端主動推送的功能例如 實時天氣、股票報價、余票顯示、消息通知等。
EventSource
是什么: EventSource的官方名稱應該是 Server-sent events(縮寫SSE)服務端派發事件,EventSource 基于http協議只是簡單的單項通信,實現了服務端推的過程客戶端無法通過EventSource向服務端發送數據。喜聞樂見的是ie并沒有良好的兼容當然也有解決的辦法比如 npm install event-source-polyfill。雖然不能實現雙向通信但是在功能設計上他也有一些優點比如可以自動重連接,event IDs,以及發送隨機事件的能力(WebSocket要借助第三方庫比如socket.io可以實現重連。)
有什么用: 因為受單項通信的限制EventSource只能用來實現像股票報價、新聞推送、實時天氣這些只需要服務器發送消息給客戶端場景中。EventSource的使用更加便捷這也是他的優點。
WebSocket & EventSource 的區別
WebSocket基于TCP協議,EventSource基于http協議。
EventSource是單向通信,而websocket是雙向通信。
EventSource只能發送文本,而websocket支持發送二進制數據。
在實現上EventSource比websocket更簡單。
EventSource有自動重連接(不借助第三方)以及發送隨機事件的能力。
websocket的資源占用過大EventSource更輕量。
websocket可以跨域,EventSource基于http跨域需要服務端設置請求頭
EventSource的實現案例
服務端代碼:
1:nodejs +express 基于自簽的https
//創建https服務
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.
*/
//根據項目的路徑導入生成的證書文件
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);
//創建https服務器
httpsServer.listen(SSLPORT, function() {
console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT);
});
格式說明
event-source必須編碼成utf-8的格式,消息的每個字段使用"\n"來做分割,并且需要下面4個規范定義好的字段:?
event: 事件類型?
data: 發送的數據?
id: 每一條事件流的ID?
retry: 告知瀏覽器在所有的連接丟失之后重新開啟新的連接等待的時間,在自動重新連接的過程中,之前收到的最后一個事件流ID會被發送到服務端。
其中data 數據的結束符必須是‘\n\n’兩個哦。
如果沒有數據發送的時候,最好定期發送以: xxx\n\n 的注釋數據 防止與瀏覽器斷開。
//添加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);
見結果:
EventSource 使用場景一版是前端只是展示數據,而有的時候因為是https,呵呵買不起證書。所以自己生成了一套證書。但是websocket不支持非法證書。所以終于找到了這個玩意兒。
java 版?https://luoyuer.com/archives/springbooteventstream.html
抓包詳解請轉到?http://www.lxweimin.com/p/3d7b0bbf435a