前端如何接收 websocket 发送过来的实时数据

  WebSocket protocol 是HTML5一种新的协议,它实现了浏览器与服务器全双工通信(full-duple)。刚开始的握手需要借助HTTP请求完成,在 WebSocket API,浏览器和服务器只需要做一个握手的动作,然后浏览器和服务器之间就形成了一条快速通道,两者之间就直接可以数据互相传送。

  那么前端如何通过 JS 发出 http 请求,又应该如何处理请求结果呢?在 initSocket() 函数中我们新建了三个 websocket 对象,通过调用这些 websocket 对象的内置函数实现数据的请求和接收:

initSocket();
function initSocket(){
  webSocket = new WebSocket('ws://'+window.location.host+'/header_soc');
  imageSocket = new WebSocket('ws://'+window.location.host+'/capture_soc');
  flashSocket = new WebSocket('ws://'+window.location.host+'/live_soc');
  //webSocket 对象
  webSocket.onerror = function (event) {
      onError(event);
  };
  webSocket.onopen = function (event) {
      onOpen(event);
  };
  webSocket.onmessage = function (event) {
      onMessage(event);
  };
  //imageSocket 对象
  imageSocket.onerror = function (event) {
      onError(event);
  };
  imageSocket.onopen = function (event) {
      onOpenImg(event);
  };
  imageSocket.onmessage = function (event) {
      onMessageImg(event);
  };
  //flashSocket 对象
  flashSocket.onerror = function (event) {
      onError(event);
  };
  flashSocket.onopen = function (event) {
      onOpenFlash(event);
  };
  flashSocket.onmessage = function (event) {
      onMessageFlash(event);
  };
}

  然后定义相应的函数,发生 http 请求,接收到数据后打印出来看一下数据格式,并进行处理

function onError(event){

}
function onOpen(event){
    webSocket.send();//看后台需要接收什么信息才能握手成功
}
function onMessage(event){
    console.log(event);
}
原文地址:https://www.cnblogs.com/goloving/p/9108462.html