websocket原理及实时投票

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

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

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

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

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

Http,  socket实现,短链接,请求响应
        - WebSocket, socket实现,双工通道,请求响应,推送,Socket创建连接,不断开。

websocket

介绍

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

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

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

socket入手实现websocket

 - 服务端(socket服务端)
            1. 服务端开启socket,监听IP和端口
            3. 允许连接
            * 5. 服务端接收到特殊值【加密sha1,特殊值,migic string="258EAFA5-E914-47DA-95CA-C5AB0DC85B11"】
            * 6. 加密后的值发送给客户端
            
            
            
            
 - 客户端(浏览器)
            2. 客户端发起连接请求(IP和端口)
            * 4. 客户端生成一个xxx,向服务端发送
            * 7. 客户端接收到加密的值
            

 1. 启动服务端

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)
# 等待用户连接
conn, address = sock.accept()
接收data
data = conn.recive(8096)

headers = get_headers(data)
获取握手消息,magic string sha1加密,然后发送给客户端
conn.send
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
get_headers,将请求头转化为字典

请求头的信息

GET /chatsocket HTTP/1.1
Host: 127.0.0.1:8002
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: http://localhost:63342
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: mnwFxiOlctXFN/DeMt1Amg==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
...
...
import socket
import base64
import hashlib

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):
    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)
    return True

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)

# 等待用户连接
conn, address = sock.accept()
# [握手消息]
data = conn.recv(8096)
headers = get_headers(data)
# for k,v in headers.items():
#     print(k,v)
magic_string =  '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
value = headers['Sec-WebSocket-Key'] + magic_string
ac = base64.b64encode(hashlib.sha1(value.encode('utf-8')).digest())

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://%s%s\r\n\r\n"
# 获取[握手消息],magic string,sha1加密
# 发送给客户端
response_str = response_tpl % (ac.decode('utf-8'), headers['Host'], headers['url'])
conn.send(bytes(response_str, encoding='utf-8'))

while True:
    info = conn.recv(8096)
    payload_len = info[1] & 127
    if payload_len == 126:
        extend_payload_len = info[2:4]
        mask = info[4:8]
        decoded = info[8:]
    elif payload_len == 127:
        extend_payload_len = info[2:10]
        mask = info[10:14]
        decoded = info[14:]
    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')

    body = body + "是正文是是"
    send_msg(conn,bytes(body,encoding='utf-8'))
socket实现server.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <script>
        ws = new WebSocket("ws://127.0.0.1:8002");
        ws.onopen = function () {
            console.log(1111);
            ws.send('hello村长')
        };
        ws.onmessage = function (event) {
            console.log(event);
        };
        ws.onclose = function () {
        }



    </script>
</body>
</html>
socket实现client端

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

2. 客户端连接

基于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()
app.py
 <!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://192.168.13.253: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>
index.html

猜你喜欢

转载自www.cnblogs.com/weidaijie/p/10503674.html