Websocket实现群聊、单聊

Websocket

使用的第三方模块:gevent-websocket

群聊

ws群聊.py中的内容

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

app = Flask(__name__)

user_socket_dict = {}


@app.route('/ws/')
def ws(user):
    # print(request.environ)
    user_socket = request.environ.get('wsgi.websocket')  # type:WebSocket
    if user_socket:
        user_socket_dict[user] = user_socket
        print(len(user_socket_dict), user_socket_dict)
    while 1:
        msg = user_socket.receive()
        print(msg)  # b"{from_user:jinwangba ,to_user:yinwangba,msg:"doushidawangba"}"
        msg_dict = json.loads(msg)
        to_usocket = user_socket_dict.get(msg_dict.get('to_user'))
        to_usocket.send(json.dumps({'from_user': user, 'to_user': msg_dict.get('to_user'), 'msg': msg_dict.get('msg')}))


@app.route('/')
def index():
    return render_template('ws.html')


if __name__ == '__main__':
    # app.run('0.0.0.0', 5000, debug=True)
    http_serv = WSGIServer(('0.0.0.0', 5000), app, handler_class=WebSocketHandler)
    http_serv.serve_forever()

ws群聊.html中的内容




    
    
    Title


发送内容:

单聊

ws.py中的内容

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

app = Flask(__name__)

user_socket_dict = {}


@app.route('/ws/')
def ws(user):
    # print(request.environ)
    user_socket = request.environ.get('wsgi.websocket')  # type:WebSocket
    if user_socket:
        user_socket_dict[user] = user_socket
        print(len(user_socket_dict), user_socket_dict)
    while 1:
        msg = user_socket.receive()
        print(msg)  # b"{from_user:jinwangba ,to_user:yinwangba,msg:"doushidawangba"}"
        msg_dict = json.loads(msg)
        to_usocket = user_socket_dict.get(msg_dict.get('to_user'))
        to_usocket.send(json.dumps({'from_user': user, 'to_user': msg_dict.get('to_user'), 'msg': msg_dict.get('msg')}))


@app.route('/')
def index():
    return render_template('ws.html')


if __name__ == '__main__':
    # app.run('0.0.0.0', 5000, debug=True)
    http_serv = WSGIServer(('0.0.0.0', 5000), app, handler_class=WebSocketHandler)
    http_serv.serve_forever()

ws.html中的内容




    
    
    Title


您的昵称:

{#

发送内容:

#}

发送:

  

 websocket握手信息及封包解包原理

import socket
import base64
import hashlib
 
#封包
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)
    return True
 
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
 
 
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(1024)
headers = get_headers(data)  # 提取请求头信息
# 对请求头中的sec-websocket-key进行加密
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 = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
value = headers['Sec-WebSocket-Key'] + magic_string
ac = base64.b64encode(hashlib.sha1(value.encode('utf-8')).digest())
response_str = response_tpl % (ac.decode('utf-8'), headers['Host'], headers['url'])
# 响应【握手】信息
conn.send(bytes(response_str, encoding='utf-8'))
 
# b'\x81\x87\xbe0\xb4\xc7\xc7Q\xda\xab\xd1^\xd3'
# msg[1] & 127
#
# 10100011
# 01111111
# 00100011 <= 125 # \x81\x87    \xbe0\xb4\xc7\xc7Q \xda\xab\xd1^\xd3'
# 00100011 == 126 # \x81\x87\xbe0\xb4    \xc7\xc7Q\xda\xab \xd1^\xd3'\xbe0\xb4\xc7\xc7Q\xda\xab\xd1^\xd3'
# 00100011 == 127 # \x81\x87 + 8个字节   内容
# mask
# for i in \xc7Q \xda\xab\xd1^\xd3':
#     \xc7Q mask
 
#解包
while True:
    info = conn.recv(8096)
    print('收到数据',info)
 
    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')
    print(body)
 
    send_msg(conn,b'nononononono')
 
conn.close()

  

 

转载于:https://www.cnblogs.com/wjs521/p/10168797.html

你可能感兴趣的:(网络,json,python)