• 使用genvent.socket实施群聊/单聊模式


    使用genvent.socket实施群聊
    from flask import Flask, request, render_template
    from gevent.pywsgi import WSGIServer
    from geventwebsocket.handler import WebSocketHandler
    from geventwebsocket.websocket import WebSocket
    
    import json
    user_dict = {}                           #设置一个公共变量
    app = Flask(__name__)
    @app.route('/ws/<username>')
    def ws(username):
        user_socket = request.environ.get('wsgi.websocket')            #获取客户端的服务
        user_dict[username] = user_socket                  #将其存到公共变量中
        while True:
            msg = user_socket.receive()    #等待接受客户端数据        
            u_msg= {'from_user':username,'chat':msg}            #将接收的数据进行处理(处理成字典)
            for uname,usocket in user_dict.items():            #循环发送向每个服务器进行发送数据
                usocket.send(json.dumps(u_msg))
    @app.route('/webchat')
    def webchat():
        return render_template('wechats.html')
    
    
    if __name__ == '__main__':
        server = WSGIServer(('0.0.0.0',9527),app,handler_class=WebSocketHandler)  #设置ip 以及端口 还有处理方式
        server.serve_forever()            #运行服务

    html文件代码

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <p>姓名: <input type="text" id="username">
        <button onclick="open_ws()">登录</button></p>
    <p>内容: <input type="text" id="message">
        <button onclick="send_msg()">发送</button></p>
    <div id="chat_list"></div>
    
    </body>
    <script type="application/javascript">
        var ws = null;
        function open_ws(){
            var username = document.getElementById("username").value;
            ws = new WebSocket('ws://192.168.16.234:9527/ws/'+username);
            ws.onopen=function(){
                alert('欢迎登录');
            };
            ws.onmessage=function(eventMessage){
                var chat = JSON.parse(eventMessage.data);
                var p =document.createElement("p");
                p.innerText=chat.from_user+':'+chat.chat;
                document.getElementById('chat_list').appendChild(p);
            }
        }
        function send_msg(){
            var msg=document.getElementById('message').value;
            ws.send(msg)
        }
    </script>
    </html>

    使用genvent.socket实施单聊模式

    import json
    from flask import Flask, request, render_template
    from geventwebsocket.handler import WebSocketHandler
    from gevent.pywsgi import WSGIServer
    user_dict = {}
    app= Flask(__name__)
    @app.route('/my_ws/<username>')
    def my_ws(username):
        user_socket=request.environ.get('wsgi.websocket')
        print(user_socket)
        user_dict[username] = user_socket
        while True:
            msg = user_socket.receive()
            msg_dict=json.loads(msg)
            msg_dict['from_user'] = username
            to_user = msg_dict.get('to_user')
            usocket= user_dict.get(to_user)
            if not usocket:
                continue
            try:
                usocket.send(json.dumps(msg_dict))
            except:
                user_dict.pop(to_user)
    
    @app.route('/wechat')
    def wechat():
        return render_template('personal.html')
    
    if __name__ == '__main__':
        server =WSGIServer(('0.0.0.0',9527),app,handler_class=WebSocketHandler)
        server.serve_forever()

    html代码:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <div id="chat_list"></div>
    <p>你的名字<input type="text" id="username">
    <button onclick="open_ws()">登录</button></p>
    <p>给: <input type="text" id="to_user"></p>
    <p><input type="text" id="message"> <button onclick="send_msg()">发送</button></p>
    
    </body>
    <script type="application/javascript">
        var ws = null;
        function open_ws() {
            var username = document.getElementById("username").value;
            ws = new WebSocket("ws://192.168.16.234:9527/my_ws/"+username);
            ws.onopen = function () {
                alert("欢迎登录");
            };
            ws.onmessage = function (eventMessage) {
                var chat = JSON.parse(eventMessage.data);
                var p = document.createElement("p");
                p.innerText = chat.from_user + ":" + chat.chat;
                document.getElementById("chat_list").appendChild(p);
            };
        }
        function send_msg() {
            var to_user = document.getElementById("to_user").value;
            var msg = document.getElementById("message").value;
            var send_str = {
              to_user:to_user,
              chat:msg
            };
            ws.send(JSON.stringify(send_str));
    
            var p = document.createElement("p");
            p.innerText = "我:" + msg;
            document.getElementById("chat_list").appendChild(p);
        }
    </script>
    </html>
  • 相关阅读:
    Python集合
    excel数据的处理
    史上最全的web前端系统学习教程!
    H5游戏开发:贪吃蛇
    javascript+HTMl5游戏下载,开发一个都能月薪上万!舅服你
    2020年必看的web前端开发学习路线!
    花了一天准备好的web前端电子书籍,全部可以免费下载!
    2019年大牛最新整理的Python技术入门路线
    从零开始,学习web前端之HTML5开发
    经验分享:如何系统学习 Web 前端技术?
  • 原文地址:https://www.cnblogs.com/shicongcong0910/p/10976435.html
Copyright © 2020-2023  润新知