WebSocket

Posted bubu99

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WebSocket相关的知识,希望对你有一定的参考价值。

技术图片
# websocket
from geventwebsocket.server import WSGIServer  # 我要WSGI为我提供服务
from geventwebsocket.handler import WebSocketHandler  # WSGI 遇到WS协议的时候,处理方式
from geventwebsocket.websocket import WebSocket  # 语法提示

# 基于Flask+geventwebsocket
from flask import Flask, request,render_template

app = Flask(__name__)

##多人聊天
user_socket_list=[]

@app.route("/ws")
def my_ws_func():
    # print(dir(request.environ))
    user_socket = request.environ.get("wsgi.websocket") #type:WebSocket
    # print(user_socket) #<geventwebsocket.websocket.WebSocket object at 0x10972fe18>
    user_socket_list.append(user_socket)
    while 1:
        msg = user_socket.receive() #等待接收客户端发送过来的消息
        for use in user_socket_list:
            # #看不到自己的发送信息
            # if use==user_socket:
            #     continue
            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");
    //当ws收到消息时执行 onmessage
    ws.onmessage = function (event) 
        console.log(event.data);
        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>
"""
群聊
技术图片
# websocket
from geventwebsocket.server import WSGIServer  # 我要WSGI为我提供服务
from geventwebsocket.handler import WebSocketHandler  # WSGI 遇到WS协议的时候,处理方式
from geventwebsocket.websocket import WebSocket  # 语法提示

# 基于Flask+geventwebsocket
from flask import Flask, request,render_template

app = Flask(__name__)


##单聊
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>
"""
单聊
技术图片
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, 3721))
sock.listen(5)
# 获取客户端socket对象
conn, address = sock.accept()
# 获取客户端的【握手】信息
data = conn.recv(1024)
print(data)
"""
b‘GET / HTTP/1.1\r\n
Host: 127.0.0.1:3721\r\n
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:68.0) Gecko/20100101 Firefox/68.0\r\n
Accept: */*\r\nAccept-Language: zh-CN,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)  # 提取请求头信息
# 对请求头中的sec-websocket-key进行加密
value = headers[Sec-WebSocket-Key] + magic_string
print(value)
ac = base64.b64encode(hashlib.sha1(value.encode(utf-8)).digest())
print(ac)
# 响应
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: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

 

以上是关于WebSocket的主要内容,如果未能解决你的问题,请参考以下文章

WebSocket的简单入门使用

WebSocket的简单入门使用

WebSocket的简单入门使用

学习cocoscreator 接触到的WebSocket的学习笔记

WebSocket的简单入门使用

websocket原理