Do you really know websocket?

Source: Internet
Author: User
Tags unpack

Old boy It education Alex Python teaching director teaches you to know WebSocket

The WebSocket protocol is a new protocol based on TCP. WebSocket was originally referred to as a TCP connection in the HTML5 specification as a placeholder for the TCP-based socket API. It implements browser-to-server full-duplex (Full-duplex) communication. The essence is to keep the TCP connection and communicate through the socket on the browser and server.

This article will use Python to write the socket server, step-by-step analysis of the request process!!!

1. Start the service side
12345678910 importsocketsock =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().........

After you start the socket server, wait for the user to "connect" and then send and receive data.

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

When a client sends a connection request to the server, not only does the connection also send a "handshake" message, and waits for the service side to respond, the connection is created successfully!

3. Establish a connection "handshake"
1234567891011121314 importsocketsock =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(‘响应【握手】信息‘)

The "handshake" information for the request and response needs to follow the rules:

    • Extracting Sec-websocket-key from the request "handshake" information
    • HMAC1 encryption with Magic_string and Sec-websocket-key, and Base64 encryption
    • Responding to the client for cryptographic results

Note: The Magic string is: 258eafa5-e914-47da-95ca-c5ab0dc85b11

Request "handshake" information as:

+ View Code

Extract the Sec-websocket-key value and encrypt it:

+ View Code4. Sending and receiving data from the client and server

The data needs to be "encapsulated" and "unpacked" when the data is transmitted by the client and the server. The client's JavaScript class library already encapsulates the "package" and "unpack" processes, but the socket server needs to be implemented manually.

First step: Get the data sent by the client "unpack"

implementation of the unpacking process based on Python (long content not implemented)

Unpack detailed process:

+ View Code

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

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

The FIN bit tells whether the last message in a series. If it ' s 0, then the server would 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 was important to know. Unfortunately, this is somewhat complicated. To read it, follow these steps:

    1. Read bits 9-15 (inclusive) and interpret, as an unsigned integer. If It's a "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-bits and interpret those as an unsigned integer. You're done .
    3. Read the next 0 bits and interpret those as an unsigned integer (the most significant bit must is). You're done .

Reading and unmasking the Data

If the MASK bit was set (and it should is, for client-to-server messages), read the next 4 octets (+ 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 O Ctet with the (i modulo 4) th octet of the MASK. In pseudo-code (so happens to be valid JavaScript):

var decoded = "";
for (var i = 0; i < encoded.length; i++) {
Decoded[i] = encoded[i] ^ mask[i% 4];
}

Now the can figure out what the decoded means depending on your application.

Step two: Send the data "packet" to the client

View Code5. Python-based implementation of a simple example

A. WebSocket server based on Python socket implementation:

+ View Code

B. Implementing a client with a JavaScript class library

+ View Code6. Implementation of web chat room based on tornado framework

Tornado is an excellent framework for supporting WebSocket, and its internal principles are as described in the steps of the step, and of course the Tornado internal encapsulation function is more complete.

The following is an example of a chat room implementation based on tornado:

app.pyindex.html

Sample source Download

Reference: Https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers

Old boy Education official website: www.oldboyedu.com

Do you really know websocket?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.