你真的了解WebSocket吗?
admin
2023-07-30 01:00:08
0

老男孩IT教育alex python教学总监教你认识WebSocket

 WebSocket协议是基于TCP的一种新的协议。WebSocket最初在HTML5规范中被引用为TCP连接,作为基于TCP的套接字API的占位符。它实现了浏览器与服务器全双工(full-duplex)通信。其本质是保持TCP连接,在浏览器和服务端通过Socket进行通信。

 本文将使用Python编写Socket服务端,一步一步分析请求过程!!!

1. 启动服务端

12345678910import socketsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)sock.bind(('127.0.0.1'8002))sock.listen(5)# 等待用户连接conn, address = sock.accept().........

启动Socket服务器后,等待用户【连接】,然后进行收发数据。

 

 

 

2. 客户端连接

1234type="text/javascript">    var socket = new WebSocket("ws://127.0.0.1:8002/xxoo");    ...</script>

 

 

当客户端向服务端发送连接请求时,不仅连接还会发送【握手】信息,并等待服务端响应,至此连接才创建成功!

 

3. 建立连接【握手】

1234567891011121314import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)sock.bind(('127.0.0.1'8002))sock.listen(5)# 获取客户端socket对象conn, address = sock.accept()# 获取客户端的【握手】信息data = conn.recv(1024).........conn.send('响应【握手】信息')

 

 

 

 

 

 

 

       

请求和响应的【握手】信息需要遵循规则:


  • 从请求【握手】信息中提取 Sec-WebSocket-Key

  • 利用magic_string 和 Sec-WebSocket-Key 进行hmac1加密,再进行base64加密

  • 将加密结果响应给客户端

注:magic string为:258EAFA5-E914-47DA-95CA-C5AB0DC85B11

请求【握手】信息为:

提取Sec-WebSocket-Key值并加密:

4.客户端和服务端收发数据

客户端和服务端传输数据时,需要对数据进行【封包】和【解包】。客户端的JavaScript类库已经封装【封包】和【解包】过程,但Socket服务端需要手动实现。

第一步:获取客户端发送的数据【解包】

你真的了解WebSocket吗? 基于Python实现解包过程(未实现长内容)

解包详细过程: 

The MASK bit simply tells whether the message is encoded. Messages from the client must be masked, so your server should expect this to be 1. (In fact, section 5.1 of the spec says that your server must disconnect from a client if that client sends an unmasked message.) When sending a frame back to the client, do not mask it and do not set the mask bit. We'll explain masking later. Note: You have to mask messages even when using a secure socket.RSV1-3 can be ignored, they are for extensions.

The opcode field defines how to interpret the payload data: 0x0 for continuation, 0x1 for text (which is always encoded in UTF-8), 0x2 for binary, and other so-called "control codes" that will be discussed later. In this version of WebSockets, 0x3 to 0x7 and 0xB to 0xF have no meaning.

The FIN bit tells whether this is the last message in a series. If it's 0, then the server will keep listening for more parts of the message; otherwise, the server should consider the message delivered. More on this later.

Decoding Payload Length

To read the payload data, you must know when to stop reading. That's why the payload length is important to know. Unfortunately, this is somewhat complicated. To read it, follow these steps:

  1. Read bits 9-15 (inclusive) and interpret that as an unsigned integer. If it's 125 or less, then that's the length; you're done. If it's 126, go to step 2. If it's 127, go to step 3.

  2. Read the next 16 bits and interpret those as an unsigned integer. You're done.

  3. Read the next 64 bits and interpret those as an unsigned integer (The most significant bit MUST be 0). You're done.

Reading and Unmasking the Data

If the MASK bit was set (and it should be, for client-to-server messages), read the next 4 octets (32 bits); this is the masking key. Once the payload length and masking key is decoded, you can go ahead and read that number of bytes from the socket. Let's call the data ENCODED, and the key MASK. To get DECODED, loop through the octets (bytes a.k.a. characters for text data) of ENCODED and XOR the octet with the (i modulo 4)th octet of MASK. In pseudo-code (that happens to be valid JavaScript):

 

var DECODED = "";
for (var i = 0; i < ENCODED.length; i++) {
    DECODED[i] = ENCODED[i] ^ MASK[i % 4];
}

 

Now you can figure out what DECODED means depending on your application.

 第二步:向客户端发送数据【封包】

你真的了解WebSocket吗? View Code

5. 基于Python实现简单示例

a. 基于Python socket实现的WebSocket服务端:

b. 利用JavaScript类库实现客户端

6. 基于Tornado框架实现Web聊天室

Tornado是一个支持WebSocket的优秀框架,其内部原理正如1~5步骤描述,当然Tornado内部封装功能更加完整。

以下是基于Tornado实现的聊天室示例:

你真的了解WebSocket吗? app.py

你真的了解WebSocket吗? index.html

示例×××

 

 参考文献:https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers 

老男孩教育官网:www.oldboyedu.com


相关内容

热门资讯

父亲的国葬,穆杰塔巴“仍未现身... 当地时间7月3日起,伊朗为2月底遇袭身亡的时任最高领袖哈梅内伊举行为期一周的国葬。葬仪首日,战争爆发...
哈梅内伊葬礼进入第二日:德黑兰... 哈梅内伊的遗体告别仪式进入第二天,伊朗国内整体氛围如何?接下来几天伊朗官方还有哪些安排?凤凰卫视记者...
视频丨加速走向全球 今年前5个... 今年以来,我国机器人出口规模持续扩大,品类结构不断优化,为高端制造出海注入新动能。 据海关统计,今年...
2026全球数字经济大会人工智... 央广网北京7月5日消息(记者 阮修星 王进文)7月3日,2026全球数字经济大会人工智能融合应用发展...
百台百成!中国航天科技四院固体... IT之家 7 月 5 日消息,北京时间 2026 年 7 月 4 日 17 时 30 分,我国在太原...
原创 固... 进入2026年7月,固态电池被推到聚光灯正中央。6月30日动力电池产业创新联盟论坛上,工信部装备一司...
“近代美国建国纪念中,唯一能和... 美国迎来建国250周年纪念,社会分裂成为本次庆典的突出底色。回望50年前同样历时十年筹备的盛会,在水...
搭讪10分钟能发生关系?披着情... 当女性被物化为“搞定”的目标,约会变成按剧本推进的标准化流程,所谓亲密感都是精心设计的陷阱近日,河南...
松木家具好吗它的优点跟缺点分别... 松木家具的优点: 优点之一:相对于其它材质的家具而言,松木家具更加环保,特别是现在许多刷过油漆的...
冰箱三层中间结冰能单开中间门吗 1、这种情况不建议单开中间门,因为即使单开中间门,化冰的效果也不是特别好。2、出现中间结冰的情况,建...