zoukankan      html  css  js  c++  java
  • WebSocket 理论知识整理

    最近工作用到websocket, 之前虽然也用到了一些简单的东西,但是并没有认真整理一下。所以这次准备了解一下WebSocket.

    WebSocket产生的背景

    WebSocket是一种在单个TCP连接上进行全双工通信的协议. 这意味着双方可以同时进行通信和交换数据

    对于我们都非常熟悉的HTTP协议,通信只能通过客户端发起,无法做到服务器主动向客户端推送消息
    这样如果在服务端出问题的时候,客户端想要知道就比较麻烦,笨的办法就是我们采用轮询的方式,每隔一段时间问一下服务端:“喂,你还在么,你怎么样了,还没死吧?” 从而来确定服务端的一些状态变化。

    关于轮询:其实就是客户端在指定的时间间隔向服务器发送请求

    但是我们都知道这种笨办法是非常浪费资源的。而WebSocket也可以说就是这样诞生了

    为什么我们需要web socket

    Internet was conceived to be a collection of Hypertext Mark-up Language (HTML) pages linking one another to form a conceptual web of information. During the course of time, static resources increased in number and richer items, such as images and began to be a part of the web fabric.

    Server technologies advanced which allowed dynamic server pages - pages whose content was generated based on a query.

    Soon, the requirement to have more dynamic web pages lead to the availability of Dynamic Hypertext Mark-up Language (DHTML). All thanks to JavaScript. Over the following years, we saw cross frame communication in an attempt to avoid page reloads followed by HTTP Polling within frames.

    However, none of these solutions offered a truly standardized cross browser solution to real-time bi-directional communication between a server and a client.

    This gave rise to the need of Web Sockets Protocol. It gave rise to full-duplex communication bringing desktop-rich functionality to all web browsers.

    WebSocket 长啥样 ?

    我们还是用HTTP来对比,我们通常访问一个网站如google,我们会在浏览器中输入:
    http://www.google.com
    或者:
    https://www.google.com

    其实webSocket和http也非常类似,如下图:

    web socket 是HTML5 规范的一部分, 允许网页和远程主机之间进行全双工通信,该协议实现以下好处:

    通过单个连接而不是两个连接使用全双工减少不必要的网络流量和延迟
    通过代理和防火墙进行流式传输,同时支持上游和下游通信

    websocket 和http 对比

    websockets 角色

    Events and Actions

    有四个主要的API events
    Open
    Message
    Close
    Error

    每一个事件都分别通过实现onopen onmessage onclose 和onerror函数来处理

    Open
    一旦客户端和服务器之间建立了连接,就会从web socket 实例触发open 事件,这个被称为客户端和服务器之间的初始握手
    一旦建立连接就会触发的事件称为onopen事件

    Message
    通常发生在服务器发送一些数据的时候触发该消息事件
    服务器发送给客户端的消息可以包括纯文本消息,二进制数据或者图像。但是无论哪种数据都会触发onmessage函数

    close
    该事件标志着服务器和客户端之间通信结束
    当触发onclose事件之后可以关闭连接,同时标记中通信结束,服务器和客户端之间无法进一步传输消息

    error
    onerror 事件之后总是随后终止连接

    Actions

    当我们想要发生某事件的时候做一些操作,通过用户显示调用的方法有:
    send()
    close()

    参考连接:http://www.ruanyifeng.com/blog/2017/05/websocket.html
    https://www.tutorialspoint.com/websockets/index.htm

  • 相关阅读:
    CPU问题导致的大量进程崩溃问题
    coredump的裁剪方法
    GDB中遍历art::Thread打印local reference的脚本
    jemalloc管理块(arena、bin)
    jemalloc存储块(region、run、chunk)
    GDB中打印pthread_internal_t的方法
    FUSE引起的SIGBUS问题分析报告
    GDB中打印ART基础类
    UC浏览器闪退问题分析报告
    『深度实战』天池小目标检测大赛·宫颈癌风险智能诊断推荐
  • 原文地址:https://www.cnblogs.com/zhaof/p/9833614.html
Copyright © 2011-2022 走看看