websocket works

# The WebSocket 
from geventwebsocket.server Import WSGIServer   # I want to serve my WSGI 
from geventwebsocket.handler Import WebSocketHandler   # WSGI protocol WS encountered when handling 
from geventwebsocket.websocket Import the WebSocket   # Syntax Tip 

# -based + geventwebsocket the Flask 
from the Flask Import the Flask, Request, the render_template 

App = the Flask ( the __name__ ) 

# # people talking 
user_socket_list = [] 

@ app.route ( " / WS " )
DEF my_ws_func ():
     # Print (dir (request.environ)) 
    user_socket = request.environ.get ( " wsgi.websocket " ) # of the type: the WebSocket 
    # Print (user_socket) # <geventwebsocket.websocket.WebSocket Object AT 0x10972fe18> 
    user_socket_list .append (user_socket)
     the while 1 : 
        msg = user_socket.receive () # waiting to receive a message sent by the client 
        for use in user_socket_list:
             # # can not see your information to send 
            # IF use == user_socket: 
            #      the Continue 
            the try :
                use.send(msg)
            except:
                continue
        # print(msg)
        # user_socket.send(msg)

@app.route("/group_chart")
def group_chart():
    return render_template("group_chart.html")


"""
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
"""

if __name__ == '__main__':
    # app.run()
    http_serv = WSGIServer(("192.168.0.103", 3721), application=app, handler_class=WebSocketHandler)
    http_serv.serve_forever()

##http://192.168.0.103:3721/group_chart



##templates/group_chart.html
"""
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>发送消息:<input type="text" id="message">
    <button onclick="send_msg()">发送</button>
</p>
<div id="message_list"></div>
</body>
<script>
    var ws = new WebSocket("ws://192.168.0.103:3721/ws");
        the console.log (the event.data);
    ws.onmessage function = (Event) {
    Onmessage // ws performed when the message is received
        var pTAG = document.createElement ( "P");
        ptag.innerText = event.data;
        var divtag = document.getElementById("message_list");
        divtag.appendChild(ptag);
    };

    function send_msg() {
        var msg = document.getElementById("message").value;
        ws.send(msg);
        document.getElementById("message").value='';
    }


</script>
</html>
"""
group chat
# The WebSocket 
from geventwebsocket.server Import WSGIServer   # I want to serve my WSGI 
from geventwebsocket.handler Import WebSocketHandler   # WSGI protocol WS encountered when handling 
from geventwebsocket.websocket Import the WebSocket   # Syntax Tip 

# -based + geventwebsocket the Flask 
from the Flask Import the Flask, Request, the render_template 

App = the Flask ( the __name__ ) 


# # single talk 
Import JSON 
user_socket_dict = {}
 "" "
'tom':<geventwebsocket.websocket.WebSocket object at 0x10972fe18>,
'rose':<geventwebsocket.websocket.WebSocket object at 0x10972fe18>
"""

@app.route("/wsone/<nickname>")
def my_func(nickname):
    user_socket = request.environ.get("wsgi.websocket") #type:WebSocket
    user_socket_dict[nickname]=user_socket
    while 1:
        msg = user_socket.receive() #等待接收客户端发送过来的消息
        msg = json.loads(msg)
        """
        {
        to_user:
        from_user:
        message:""
        }
        """
        print(msg)
        to_user_socket = user_socket_dict.get(msg.get('to_user'))
        to_user_socket.send(json.dumps(msg))


@app.route("/one_chart")
def group_chart():
    return render_template("one_chart.html")

"""
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
"""

if __name__ == '__main__':
    # app.run()
    http_serv = WSGIServer(("192.168.0.103", 3721), application=app, handler_class=WebSocketHandler)
    http_serv.serve_forever()

##http://192.168.0.103:3721/one_chart 都登陆以后聊天



#templates/one_chart.html
"""
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>登陆 <input type="text" id="nick"><button onclick="login()">登陆</button></p>
<p>给:<input type="text" id="to_user"></p>
<p>发送消息:<input type="text" id="message">
    <button onclick="send_msg()">发送</button>
</p>
<div id="message_list"></div>
</body>
<script>

    var ws = null;

    function send_msg() {
        var msg = document.getElementById("message").value;
        var to_user =document.getElementById('to_user').value;
        var nick = document.getElementById('nick').value;
        var msg_obj={
            to_user:to_user,
            from_user:nick,
            msg:msg,
        };
        var msg_json = JSON.stringify(msg_obj);
        ws.send(msg_json);
    }

    function login() {
        var nick = document.getElementById('nick').value;
        ws = new WebSocket("ws://192.168.0.103:3721/wsone/"+nick);
        //当ws收到消息时执行 onmessage
        ws.onmessage = function (event) {
            console.log(event.data);
            data_obj=JSON.parse(event.data);
            var ptag = document.createElement("p");

            ptag.innerText = data_obj.from_user+':'+ data_obj.msg;

            var divtag = document.getElementById("message_list");
            divtag.appendChild(ptag);
        };

    }


</script>
</html>
"""
Single chat
Import Socket, Base64, hashlib 

our sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM) 
sock.setsockopt (socket.SOL_SOCKET, socket.SO_REUSEADDR, . 1 ) 
sock.bind (( ' 127.0.0.1 ' , 3721 )) 
our sock. the listen ( 5 )
 # get the client socket object 
conn, address = sock.accept ()
 # get the client [handshake] information 
the Data = conn.recv (1024 )
 Print (the Data)
 "" " 
b'GET / HTTP / 1.1 \ R & lt \ n- 
the Host: 127.0.0.1:3721\r\n  
the User-Agent: Mozilla / 5.0 (Macintosh; Intel Mac OS the X-10.14; rv: 68.0) Gecko / Firefox 20,100,101 / 68.0 \ r \ the n-
the Accept: * / * \ R & lt \ nAccept-Language: the CN-ZH, ZH; Q = 0.8, ZH-TW; Q = 0.7, ZH-HK; Q = 0.5, en-US; q = 0.3, en; q = 0.2 \ r \ n
Accept-Encoding: gzip, deflate\r\n
Sec-WebSocket-Version: 13\r\n
Origin: http://localhost:63342\r\n
Sec-WebSocket-Extensions: permessage-deflate\r\n
Sec-WebSocket-Key: 9hCIuQr2e0nm9/5ZfpihZg==\r\n
Connection: keep-alive, Upgrade\r\n
Pragma: no-cache\r\n
Cache-Control: no-cache\r\n
Upgrade: websocket\r\n\r\n'
"""

# magic string为:258EAFA5-E914-47DA-95CA-C5AB0DC85B11
magic_string = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'

# 取出Sec-WebSocket-Key
def get_headers(data):
    header_dict = {}
    header_str = data.decode("utf8")
    for i in header_str.split("\r\n"):
        if str(i).startswith("Sec-WebSocket-Key"):
            header_dict["Sec-WebSocket-Key"] = i.split(":")[1].strip()
    return header_dict


# def get_header(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 
# 


headers = get_headers (Data)   #Extracting header information request 
# of sec-websocket-key request header is encrypted 
value = headers [ ' Sec-a WebSocket-Key ' ] + magic_string
 Print (value) 
AC = base64.b64encode (hashlib.sha1 (value.encode ( ' UTF-. 8 ' .)) Digest ())
 Print (AC)
 # response 
response_tpl = " the HTTP / 1.1 101 Switching Protocols \ R & lt \ n- " \
                " Upgrade: WebSocket \ R & lt \ n- " \
                " Connection: Upgrade \ R & lt \ n- " \
                " Sec-a WebSocket the Accept-:% S \ R & lt \ n- " \
               "WebSocket-Location: ws://127.0.0.1:3721\r\n\r\n"

response_str = response_tpl % (ac.decode('utf-8'))
# 响应【握手】信息
conn.send(response_str.encode("utf8"))

while True:
    msg = conn.recv(8096)
    print(msg)


##
"""
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
</body>
<script>
    var ws = new WebSocket("ws://127.0.0.1:3721");
    ws.onmessage = function (event) {
        console.log(event.data);
    };
</script>
</html>
"""
WebSocket
# B '\ X81 \ X83 \ xceH \ XB6 \ X85 \ xffz \ X85' 

hashstr = B ' \ X81 \ X83 \ xceH \ XB6 \ X85 \ xffz \ X85 ' 
# B '\ X81 \ X83 \ xceH \ XB6 \ X85 \ xffz \ X85 ' 

# the second byte is \ X83 9-16 bit for bit operation and 127 
payload hashstr = [. 1] 127 & Print (payload)
 IF payload == 127 : 
    extend_payload_len = hashstr [2 10: ] 
    mask [10:14 = hashstr ] 
    Decoded = hashstr [14 :]
 # when the calculation result is equal to 127 bits, then the first byte of the data length of 3-10 
# 11-14 bytes necessary to decrypt the mask string 
# then the data for the first 15 bytes to the end of the IF payload 126 ==


 :
    extend_payload_len = hashstr [2:. 4 ] 
    mask = hashstr [. 4:. 8 ] 
    Decoded = hashstr [. 8 :]
 # When the calculation result is equal to 126 bits, then the first byte of the data length of 3-4 
# 5-8 byte mask is required to decrypt the string 
# , the data byte to the end of the 9th 


iF payload <= 125 : 
    extend_payload_len = None 
    mask = hashstr [2:. 6 ] 
    Decoded = hashstr [. 6 :] 

# when the 125-bit result is less time , then this number is the length of the data 
# 3-6 bytes required to decrypt the mask string 
# , the data for the first 7 bytes to the end 

str_byte = ByteArray () # array streams 

for Iin range(len(decoded)):
    byte = decoded[i] ^ mask[i % 4]
    str_byte.append(byte)

print(str_byte.decode("utf8"))
Decryption
import struct
msg_bytes = "hello".encode("utf8")
token = b"\x81"
length = len(msg_bytes)

if length <= 254:
    token += struct.pack("B", length)
elif length <= 65535:
    token += struct.pack("!BH", 126, length)
else:
    token += struct.pack("!BQ", 127, length)

msg = token + msg_bytes

print(msg)
encryption

 

Guess you like

Origin www.cnblogs.com/bubu99/p/11324666.html