標籤:oop com disco pre java comment table type nbsp
老男孩IT教育alex python教學總監教你認識WebSocket
WebSocket協議是基於TCP的一種新的協議。WebSocket最初在HTML5規範中被引用為TCP串連,作為基於TCP的通訊端API的預留位置。它實現了瀏覽器與伺服器全雙工系統(full-duplex)通訊。其本質是保持TCP串連,在瀏覽器和服務端通過Socket進行通訊。
本文將使用Python編寫Socket服務端,一步一步分析請求過程!!!
1. 啟動服務端
| 12345678910 |
import 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. 用戶端串連
| 1234 |
<script type="text/javascript"> var socket = new WebSocket("ws://127.0.0.1:8002/xxoo"); ...</script> |
當用戶端向服務端發送串連請求時,不僅串連還會發送【握手】資訊,並等待服務端響應,至此串連才建立成功!
3. 建立串連【握手】
| 1234567891011121314 |
import 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
請求【握手】資訊為:
+ View Code
提取Sec-WebSocket-Key值並加密:
+ View Code4.用戶端和服務端收發資料
用戶端和服務端傳輸資料時,需要對資料進行【封包】和【解包】。用戶端的JavaScript類庫已經封裝【封包】和【解包】過程,但Socket服務端需要手動實現。
第一步:擷取用戶端發送的資料【解包】
基於Python實現解包過程(未實現長內容)
解包詳細過程:
+ View Code
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:
- 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.
- Read the next 16 bits and interpret those as an unsigned integer. You‘re done.
- 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.
第二步:向用戶端發送資料【封包】
View Code5. 基於Python實現簡單樣本
a. 基於Python socket實現的WebSocket服務端:
+ View Code
b. 利用JavaScript類庫實現用戶端
+ View Code6. 基於Tornado架構實現Web聊天室
Tornado是一個支援WebSocket的優秀架構,其內部原理正如1~5步驟描述,當然Tornado內部封裝功能更加完整。
以下是基於Tornado實現的聊天室樣本:
app.py index.html
樣本源碼下載
參考文獻:https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers
老男孩教育官網:www.oldboyedu.com
你真的瞭解WebSocket嗎?