zoukankan      html  css  js  c++  java
  • 前端如何接收 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);
    }
  • 相关阅读:
    vscode的一些常用、神奇操作
    vue2.x中使用v-model进行父传子
    js设置,获取,删除cookies
    Linux虚拟机克隆后网卡UUID问题
    jQuery ajax 请求HttpServlet返回[HTTP/1.1 405 Method not allowed]
    byte、二进制、十进制数值之间的转换
    sqlite-jdbc jar包下载过程笔记
    windows系统bat方式启动tomcat出现java.lang.OutOfmemoryError:PermGen Space 错误
    DIV内容垂直居中
    在HTML中实现和使用遮罩层
  • 原文地址:https://www.cnblogs.com/goloving/p/9108462.html
Copyright © 2011-2022 走看看