• Websocket 群聊功能


    websocket 群聊

    前提关闭防火墙

    写入代码

    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():
        # print(request.environ)
        """
        wsgi.websocket:<geventwebsocket.websocket.WebSocket object at 0x0000000003Bc8528>
        :return:
        """
        user_socket = request.environ.get("wsgi.websocket")
        user_socket_list.append(user_socket)
        while True:
    
            msg =user_socket.receive()
            print(msg)
            for usocket in user_socket_list:
                usocket.send(msg)
                #user_socket.send(msg)
    
        #1 已经开启的websocket连接
        #3 开启了websocket连接 然后 断开了
    
    
        # return "123"
    @app.route("/")
    def index():
        return  render_template("my_ws.html")
    
    if __name__ =="__main__":
        http_serv = WSGIServer(("0.0.0.0",9527),app,handler_class=WebSocketHandler)
        http_serv.serve_forever()
    ws_serv
    <!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.78:9527/conn_ws");   // 自己的ip地址,页面才往自己页面显示内容
        ws.onmessage =function (messageEvent) {
            console.log(messageEvent.data);
            var ptag = document.createElement("p");
            ptag.innerText =messageEvent.data;
            document.getElementById("chat_list").appendChild(ptag);
        };
        function send() {
            var send_str = document.getElementById("send_str").value;
            ws.send(send_str);
        }
    
    </script>
    
    </html>
    my_ws.html

    这样就可以群聊了

  • 相关阅读:
    Docker 容器相关命令
    Docker 镜像相关命令
    Docker 守护进程相关命令
    VMware Workstation 报w32authconnectionlaunch:readfile失败
    关于 Vue Baidu Map 自动定位
    前端面试题第一天
    记录一下使用element ui使用级联选择器的坑,级联选择器的默认选中
    判断值得类型,以及判断对象是否为空对象
    js计算两个时间差
    关于axios请求携带cookie以及封装
  • 原文地址:https://www.cnblogs.com/tianshuai1/p/10587958.html
Copyright © 2020-2023  润新知