search
HomeWeb Front-endH5 TutorialWebsocket 协议解析

Websocket 协议解析

Mar 30, 2017 pm 02:38 PM

WebSocket protocol 是HTML5一种新的协议。它是实现了浏览器与服务器全双工通信(full-duplex)。

       现 很多网站为了实现即时通讯,所用的技术都是轮询(polling)。轮询是在特定的的时间间隔(如每1秒),由浏览器对服务器发出HTTP request,然后由服务器返回最新的数据给客服端的浏览器。这种传统的HTTP request 的模式带来很明显的缺点 – 浏览器需要不断的向服务器发出请求,然而HTTP request 的header是非常长的,里面包含的数据可能只是一个很小的值,这样会占用很多的带宽。

       而最比较新的技术去做轮询的效果是Comet – 用了AJAX。但这种技术虽然可达到全双工通信,但依然需要发出请求。

       在 WebSocket API,浏览器和服务器只需要要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送,改变了原有的B/S模式。

1099.png

 在这里是关于Websocket在 php 中的实现,这篇文章里,我主要对websocket 协议进行一个简单的介绍。

Websocket 业务模型

1110.png

浏览器端的websocket 请求一般是

 // javacsript
  var ws = new WebSocket("ws://127.0.0.1:4000");
  ws.onopen = function(){
    console.log("succeed");
  };
  ws.onerror = function(){
    console.log(“error”);
  };
  ws.onmessage = function(e){
  console.log(e); 
  }

当 new 一个 websocket 对象之后,就会向服务器发送一个 get 请求

1111.png

这个请求是对摸个服务器的端口发送的,一般的话,会预先在服务器将一个socket 绑定到一个端口上,客户端和服务器端在这个预定的端口上通信(我这里绑定的就是 4000 端口,默认情况下,websocke 使用 80 端口)。

       然 后,在服务器端的socket监听到这个packet 之后就生成一个新的 socket,将发送过来的数据中的 Sec-WebSocket-Key 解析出来,然后按照把“Sec-WebSocket-Ke”加上一个魔幻字符串“258EAFA5-E914-47DA-95CA- C5AB0DC85B11”。使用SHA-1加密,之后进行BASE-64编码,将结果做为“Sec-WebSocket-Accept”头的值,返回给 客户端。

       客户端收到这个之后,就会将 通信协议 upgrade 到 websocket 协议。

1112.png

然后就会在这个持久的通道下进行通信,包括浏览器的询问,服务器的push,双方是在一个全双工的状态下相互通信。 切换后的websocket 协议中的 数据传输帧的格式(此时不再使用html协议) 官方文档给出的说明:

1113.jpg

       直接看这个,谁都会有点头大: 我花了一幅图来简单的解释这个 frame 的结构。

1114.png

各字段的解释:

FIN              1bit 表示信息的最后一帧,flag,也就是标记符

RSV 1-3        1bit each 以后备用的 默认都为 0

Opcode         4bit 帧类型,

Mask              1bit 掩码,是否加密数据,默认必须置为1 

Payload len   7bit 数据的长度,当这个7 bit的数据 == 126 时,后面的2 个字节也是表示数     据长度,当它 == 127 时,后面的 8 个字节表示数据长度Masking-key      1 or 4 bit 掩码Payload data  playload len  bytes 数据

       所以我们这里的代码,通过判断 Playload len的值,来用 substr 截取 Masking-key 和 PlayloadData。

       根据掩码解析数据的方法是:

for( i = 0; i < data.length ; i++){
   orginalData += data[i]  ^  maskingKey[i mod 4]; 
}

  在PHP中,当我们收到数据之后,按照这里的格式截取数据,并将其按照这里的方法解析后就得到了浏览器发送过来的数据。 当我们想把数据发送给浏览器时,也要按照这个格式组装frame。 这里是我的方法:

function frame($s){
   $a = str_split($s, 125);
   if (count($a) == 1){
   return "\x81" . chr(strlen($a[0])) . $a[0];
   }
   $ns = "";
   foreach ($a as $o){
   $ns .= "\x81" . chr(strlen($o)) . $o;
   }
   return $ns;
  }

 强 行将要发送的数据分割成 125 Byte / frame,这样 playload len 只需要 7 bits。也就是直接将数据的长度的ascall码拼接上去,然后后面跟上要发送的数据。 每一个 frame 前面加的 ‘\x81’ 用二进制就是: 1000 0001 1000 :

1 是 FIN

000 是三个备用的bit

0001 : 指的是 opcode 官方的解释:

1115.jpg

       可以设置 opcode的值,来告诉浏览器这个frame的数据属性。

以上就是Websocket 协议解析的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Beyond Basics: Advanced Techniques in H5 CodeBeyond Basics: Advanced Techniques in H5 CodeMay 02, 2025 am 12:03 AM

Advanced tips for H5 include: 1. Use complex graphics to draw, 2. Use WebWorkers to improve performance, 3. Enhance user experience through WebStorage, 4. Implement responsive design, 5. Use WebRTC to achieve real-time communication, 6. Perform performance optimization and best practices. These tips help developers build more dynamic, interactive and efficient web applications.

H5: The Future of Web Content and DesignH5: The Future of Web Content and DesignMay 01, 2025 am 12:12 AM

H5 (HTML5) will improve web content and design through new elements and APIs. 1) H5 enhances semantic tagging and multimedia support. 2) It introduces Canvas and SVG, enriching web design. 3) H5 works by extending HTML functionality through new tags and APIs. 4) Basic usage includes creating graphics using it, and advanced usage involves WebStorageAPI. 5) Developers need to pay attention to browser compatibility and performance optimization.

H5: New Features and Capabilities for Web DevelopmentH5: New Features and Capabilities for Web DevelopmentApr 29, 2025 am 12:07 AM

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.