zoukankan      html  css  js  c++  java
  • websocket原理

    import socket, base64, hashlib
    
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('127.0.0.1', 9527))
    sock.listen(5)
    # 获取客户端socket对象
    conn, address = sock.accept()
    # 获取客户端的【握手】信息
    data = conn.recv(1024)
    print(data)
    """
    GET /ws HTTP/1.1
    
    Host: 127.0.0.1:9527
    
    Connection: Upgrade
    
    Pragma: no-cache
    
    Cache-Control: no-cache
    
    User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
    
    Upgrade: websocket
    
    Origin: http://localhost:63342
    
    Sec-WebSocket-Version: 13
    
    Accept-Encoding: gzip, deflate, br
    
    Accept-Language: zh-CN,zh;q=0.9
    
    Cookie: session=a6f96c20-c59e-4f33-84d9-c664a2f29dfc
    
    Sec-WebSocket-Key: MAZZU5DPIxWmhk/UWL2+BA==
    
    Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
    
    
    """
    # 以下动作是由websockethandler完成的
    # magic string为:258EAFA5-E914-47DA-95CA-C5AB0DC85B11
    
    
    def get_headers(data):
        header_dict = {}
        header_str = data.decode("utf8")
        for i in header_str.split("
    "):
            if str(i).startswith("Sec-WebSocket-Key"):
                header_dict["Sec-WebSocket-Key"] = i.split(":")[1].strip()
    
        return header_dict
    
    
    headers = get_headers(data)  # 提取请求头信息
    #
    magic_string = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
    #Sec-WebSocket-Key: MAZZU5DPIxWmhk/UWL2+BA==
    value = headers['Sec-WebSocket-Key'] + magic_string
    print(value)
    ac = base64.b64encode(hashlib.sha1(value.encode('utf-8')).digest())
    
    # 对请求头中的sec-websocket-key进行加密
    response_tpl = "HTTP/1.1 101 Switching Protocols
    " 
                   "Upgrade:websocket
    " 
                   "Connection: Upgrade
    " 
                   "Sec-WebSocket-Accept: %s
    " 
                   "WebSocket-Location: ws://127.0.0.1:9527
    
    "
    print(ac.decode('utf-8'))
    response_str = response_tpl % (ac.decode('utf-8'))
    # 响应【握手】信息
    conn.send(response_str.encode("utf8"))
    #
    while True:
        msg = conn.recv(8096)
        print(msg)
    View Code
  • 相关阅读:
    C++中int与string的相互转换【转】
    C# 获取文件名及扩展名【转】
    k8s查看容器日志---查看运行中指定pod以及指定pod中容器的日志
    shell字符串截取
    Kubernetes集群之清除集群
    Expect Command And How To Automate Shell Scripts Like Magic
    CentOS 7搭建本地yum源和局域网yum源
    使用MobaXterm配置ssh隧道(port forwarding)
    重置jenkins用户名密码
    Kubernetes之Taints与Tolerations 污点和容忍
  • 原文地址:https://www.cnblogs.com/s593941/p/10269136.html
Copyright © 2011-2022 走看看