websocket

websocket的由来

我们知道http协议是短连接,一次请求一次响应,如果我们想给客户端推送消息,或者想实时的获取数据我们是怎么做的呢?

为了伪造这种效果我们用了轮询和长轮询,但是这里也有弊端,服务端只能够做出响应,且不能够主动推送消息.

那么诞生了一个新的协议,websocket协议,是基于http协议创建的.

他能够不断开连接的实时收发数据,且服务端能够主动的给客户端推送消息

websocket

介绍

#1. 什么是websocket?
    是一套协议,协议规定了:
        - 连接时需要握手
        - 发送数据进行加密
        - 连接之后不断开
#2. websocket意义?
        实时的响应页面,且可以主动给客户端推送消息

#3.websocket的兼容性 
    ie浏览器

#4.哪些框架支持websocket?
        - flask gevent-websocket
        - django channel
        以上默认不支持
        -tornado 框架自带

基于flask的websocket应用

安装第三方包:

pip install gevent-websocket

基于websocket的实时投票实例:

from flask import Flask,render_template,request
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
import json

app = Flask(__name__)

USERS = {
    '1':{'name':'钢弹','count':0},
    '2':{'name':'铁锤','count':0},
    '3':{'name':'贝贝','count':100},
}


# http://127.0.0.1:5000/index
@app.route('/index')
def index():
    return render_template('index.html',users=USERS)

# http://127.0.0.1:5000/message
WEBSOCKET_LIST = []
@app.route('/message')
def message():
    ws = request.environ.get('wsgi.websocket')
    if not ws:
        print('http')
        return '您使用的是Http协议'
    WEBSOCKET_LIST.append(ws)
    while True:
        cid = ws.receive()
        if not cid:
            WEBSOCKET_LIST.remove(ws)
            ws.close()
            break
        old = USERS[cid]['count']
        new = old + 1
        USERS[cid]['count'] = new
        for client in WEBSOCKET_LIST:
            client.send(json.dumps({'cid':cid,'count':new}))

if __name__ == '__main__':
    http_server = WSGIServer(('0.0.0.0', 5000), app, handler_class=WebSocketHandler)
    http_server.serve_forever()

html:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <h1>丑男投票系统</h1>
    <ul>
        {% for k,v in users.items() %}
            <li onclick="vote({{k}})" id="id_{{k}}">{{v.name}}<span>{{v.count}}</span></li>
        {% endfor %}
    </ul>

    <script src="{{ url_for('static',filename='jquery-3.3.1.min.js')}}"></script>
    <script>
        var ws = new WebSocket('ws://127.0.0.1:5000/message')
        ws.onmessage = function (event) {
            /* 服务器端向客户端发送数据时,自动执行 */
            // {'cid':cid,'count':new}
            var response = JSON.parse(event.data);
            $('#id_'+response.cid).find('span').text(response.count);

        };
        function vote(cid) {
            ws.send(cid)
        }
    </script>
</body>
</html>

websocket原理

websocket原理:
        1. 服务端运行,等待客户端连接
        2. 客户端来连接,服务端同意.
        3. 客户端立即发送一个"握手信息"
        4. 服务端接受到握手信息后需要对数据进行加密,给客户端返回
            -sec-WebSocket-Key + magic_string
            -sha1 加密
            -base64 加密
        双方可以互相通信
        5. 客户端给服务端发送消息:
            读取第二个字节的后7位
                127:头10字节, 4字节masking key
                126:头4字节,  4字节masking key
                <=125:头2字节,4字节masking key
                
        6.服务端给客户端发送消息:
# by luffycity.com

def get_headers(data):
    """
    将请求头格式化成字典
    :param data:
    :return:
    """
    header_dict = {}
    data = str(data, encoding='utf-8')
    header, body = data.split('\r\n\r\n', 1)
    header_list = header.split('\r\n')
    for i in range(0, len(header_list)):
        if i == 0:
            if len(header_list[i].split(' ')) == 3:
                header_dict['method'], header_dict['url'], header_dict['protocol'] = header_list[i].split(' ')
        else:
            k, v = header_list[i].split(':', 1)
            header_dict[k] = v.strip()
    return header_dict


def send_msg(conn, msg_bytes):
    """
    WebSocket服务端向客户端发送消息
    :param conn: 客户端连接到服务器端的socket对象,即: conn,address = socket.accept()
    :param msg_bytes: 向客户端发送的字节
    :return:
    """
    import struct

    token = b"\x81"
    length = len(msg_bytes)
    if length < 126:
        token += struct.pack("B", length)
    elif length <= 0xFFFF:
        token += struct.pack("!BH", 126, length)
    else:
        token += struct.pack("!BQ", 127, length)

    msg = token + msg_bytes
    conn.send(msg)


import base64
import hashlib
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)
#####################1. 等待用户连接##################
conn, address = sock.accept()

##################2. 接收验证消息##################
msg = conn.recv(8096)
msg_dict = get_headers(msg)
################### 3. 对数据加密##################
value = msg_dict['Sec-WebSocket-Key'] + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
ac = base64.b64encode(hashlib.sha1(value.encode('utf-8')).digest())
# print(ac,type(ac))
################### 4.将加密后的结果返回给客户端##################
response_tpl = "HTTP/1.1 101 Switching Protocols\r\n" \
      "Upgrade:websocket\r\n" \
      "Connection: Upgrade\r\n" \
      "Sec-WebSocket-Accept: %s\r\n" \
      "WebSocket-Location: ws://127.0.0.1:8002\r\n\r\n"
response = response_tpl %(ac.decode('utf-8'),)
conn.send(response.encode('utf-8'))



################### 5. 接收小强发送的数据##################
while True:
    info = conn.recv(8096)
    payload_len = info[1] & 127

    if payload_len == 127:
        extend_payload_len = info[2:10]
        mask = info[10:14]
        decoded = info[14:]
    elif payload_len == 126:
        extend_payload_len = info[2:4]
        mask = info[4:8]
        decoded = info[8:]
    else:
        extend_payload_len = None
        mask = info[2:6]
        decoded = info[6:]

    bytes_list = bytearray()
    for i in range(len(decoded)):
        chunk = decoded[i] ^ mask[i % 4]
        bytes_list.append(chunk)
    body = str(bytes_list, encoding='utf-8')
    print(body)

    ##################服务端主动推送消息##################
    import  time
    time.sleep(2)
    #进行封包
    send_msg(conn,b'123123123')

 

posted @ 2018-09-02 16:25  R00M  阅读(107)  评论(0编辑  收藏  举报