• WebSocket


    HTTP的生命周期通过 Request 来界定,也就是一个 Request 一个 Response ,那么在 HTTP1.0 中,这次HTTP请求就结束了。

    在HTTP1.1中进行了改进,使得有一个keep-alive,也就是说,在一个HTTP连接中,可以发送多个Request,接收多个Response。但是请记住 Request = Response, 在HTTP中永远是这样,也就是说一个request只能有一个response。而且这个response也是被动的,不能主动发起。

    import json
    
    from flask import Flask,request,render_template
    
    from geventwebsocket.handler import WebSocketHandler
    from gevent.pywsgi import WSGIServer
    from geventwebsocket.websocket import WebSocket
    
    app = Flask(__name__)
    
    user_socket_dict = {}
    
    @app.route("/conn_ws/<user_nick>")
    def ws_app(user_nick):
    
        user_socket = request.environ.get("wsgi.websocket")  # type:WebSocket 会有提示语句
        user_socket_dict[user_nick] = user_socket
        print(len(user_socket_dict),list(user_socket_dict.keys()))
    
        while True:
            msg = user_socket.receive()  #接受消息
            msg_dict = json.loads(msg)
            to_user = msg_dict.get("to_user")
            to_user_socket = user_socket_dict.get(to_user)
            to_user_socket.send(msg) #回复消息
    
    
    @app.route("/")
    def index():
        return render_template("my_ws.html")
    
    
    if __name__ == '__main__':
        # app.run()
        http_serv = WSGIServer(("0.0.0.0",9527),app,handler_class=WebSocketHandler) #设置websocket
        http_serv.serve_forever() #启动websocket

    单聊

    import json
    
    from flask import Flask,request,render_template
    
    from geventwebsocket.handler import WebSocketHandler
    from gevent.pywsgi import WSGIServer
    from geventwebsocket.websocket import WebSocket
    
    app = Flask(__name__)
    
    user_socket_dict = {}
    
    @app.route("/conn_ws/<user_nick>")
    def ws_app(user_nick):
    
        user_socket = request.environ.get("wsgi.websocket")  # type:WebSocket
        user_socket_dict[user_nick] = user_socket
        print(len(user_socket_dict),list(user_socket_dict.keys()))
    
        while True:
            msg = user_socket.receive()
            msg_dict = json.loads(msg)
            to_user = msg_dict.get("to_user")
            to_user_socket = user_socket_dict.get(to_user)
            to_user_socket.send(msg)
    
    
    @app.route("/")
    def index():
        return render_template("my_ws.html")
    
    
    if __name__ == '__main__':
        # app.run()
        http_serv = WSGIServer(("0.0.0.0",9527),app,handler_class=WebSocketHandler)
        http_serv.serve_forever()
    py
    <!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>
    发送给:<input type="text" id="to_user">消息:<input type="text" id="send_str">
    <button id="send_btn" onclick="send()">发送消息</button>
    <p>
    <div id="chat_list">
    
    </div>
    </p>
    </body>
    <script type="application/javascript">
        var ws = null;
        // ws.onopen = function(){
        //     ws.send("123");
        // }
    
        function login() {
            var nick = document.getElementById("nick").value;
            ws = new WebSocket("ws://192.168.11.133:9527/conn_ws/"+nick);
            ws.onmessage = function (messageEvent) {
                console.log(messageEvent.data);
                var ptag = document.createElement("p");
    
                var message = JSON.parse(messageEvent.data);
    
                ptag.innerText =message.from_user + " : " + message.message ;
                document.getElementById("chat_list").appendChild(ptag);
            };
        }
    
        // document.getElementById("send_btn").addEventListener("onclick",)
        function send() {
            var message = document.getElementById("send_str").value;
            var send_str = {
                from_user:document.getElementById("nick").value,
                to_user:document.getElementById("to_user").value,
                message:message
            };
            var json_send_str = JSON.stringify(send_str);
            ws.send(json_send_str);
        }
    </script>
    </html>
    html

    群聊

    from flask import Flask,request,render_template
    
    from geventwebsocket.handler import WebSocketHandler
    from gevent.pywsgi import WSGIServer
    from geventwebsocket.websocket import WebSocket
    
    app = Flask(__name__)
    
    user_socket_list = []
    
    @app.route("/conn_ws")
    def ws_app():
    
        user_socket = request.environ.get("wsgi.websocket")  # type:WebSocket
        user_socket_list.append(user_socket)
        print(len(user_socket_list),user_socket_list)
    
        while True:
            msg = user_socket.receive()
            print(msg)
    
            for usocket in  user_socket_list:
                usocket.send(msg)
    
        
    
    
    @app.route("/")
    def index():
        return render_template("my_ws.html")
    
    
    if __name__ == '__main__':
        # app.run()
        http_serv = WSGIServer(("0.0.0.0",9527),app,handler_class=WebSocketHandler)
        http_serv.serve_forever()
    .py
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    
    </head>
    <body>
    <input type="text" id="send_str">
    <button id="send_btn" onclick="send()">发送消息</button>
    <p>
    <div id="chat_list">
    
    </div>
    </p>
    </body>
    <script type="application/javascript">
        var ws = new WebSocket("ws://192.168.11.133:9527/conn_ws");
        ws.onmessage = function (messageEvent) {
            console.log(messageEvent.data);
            var ptag = document.createElement("p");
            ptag.innerText = messageEvent.data;
            document.getElementById("chat_list").appendChild(ptag);
        };
    
        // document.getElementById("send_btn").addEventListener("onclick",)
        function send() {
            var send_str = document.getElementById("send_str").value;
            ws.send(send_str);
        }
    </script>
    </html>
    html
  • 相关阅读:
    如何找bug
    信号量
    带组装的测试
    Oracle的一些操作
    NPOI的操作
    初次认识 C# win32 api
    C# 通过Selecnuim WebDriver操作非IE浏览器
    DevExpress.chartControt画趋势图
    DevExpress.chartContro控件保存图片和打印图片
    SqlServer基础复习
  • 原文地址:https://www.cnblogs.com/wanglan/p/10581333.html
Copyright © 2020-2023  润新知