先後端通信的幾種方式

EventSource

  • 使用方法
var evtSource = new EventSource(url); // 服務器URL
  • 接收
evtSource.onmessage = function(e) {
  var newElement = document.createElement("li");
  
  newElement.innerHTML = "message: " + e.data;
  document.body.appendChild(newElement);
}
  • 其它類型的事件
evtSource.addEventListener("ping", function(e) {
  var newElement = document.createElement("li");
  
  var obj = JSON.parse(e.data);
  newElement.innerHTML = "ping at " + obj.time;
  document.body.appendChild(newElement);
}, false);

web code demo
server code demojavascript

服務器端中在傳輸數據時將頭中的Content-Type設置爲text/event-stream


WebSocket

  • 使用方法
var ws = new WebSocket("ws://localhost:8080", [protocols]);
  • 屬性java

    • ws.binaryType //使用二進制的數據類型鏈接
    • ws.protocol //服務器選擇的下屬協議只讀
    • ws.readyState //連接狀態只讀
    • ws.bufferedAmount //未發送至服務器的字節數只讀
    • ws.extensions //服務器選擇的擴展只讀
    • ws.onclose //關閉前的回調函數
    • ws.onerror //鏈接失敗後的回調函數
    • ws.onmessage //從服務器接受到信息時的回調函數
    • ws.onopen //鏈接成功後的回調函數
    • ws.url //WebSocket的絕對路徑
  • 方法git

    • ws.close([code[, reason]]) //關閉當前連接
    • ws.send(data) //發送數據
  • 工具github

    • Socket.io //基於長輪詢/WebSocketNode.js庫,包括客戶端
    • ws //WebSocket客戶端和服務器 Node.js庫

Ajax

  • 簡介web

    • 新技術的一種集合
    • 其中包括:HTML or XHTML, Cascading Style Sheets, JavaScript, The Document Object Model, XML, XSLT, 以及最重要的 XMLHttpRequest object
  • XMLHttpRequest (XHR)json

    • 能夠用來獲取任何類型的數據,還支持ftp協議
    • 使用方法
    var req = new XMLHttpRequest();
      req.onload = (e)=>{}; // ES6語法
      req.onreadystatechange = (e)=>{/*req.readyState*//*req.status*/}
      req.onerror = (e)=>{};
      req.open(protocol, url, async);
      req.setRequestHeader(); // 設置請求頭
      req.send([params]); //POST時能夠填寫params String,GET使用url形式傳遞數據
      
      //POST能夠傳輸json,對數據沒有限制等.GET只能以key-value形式傳遞數據,使用&符鏈接

2018-11-9 17:33

WebRTC(我所理解的並不屬於先後端通信方式,屬於p2p通信)

文章更新中...async

相關文章
相關標籤/搜索