Flask请求上下文源码讲解,简单的群聊单聊web

请求上下文流程图

 

群聊html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p><input type="text" id="nickname">
    <button onclick="create_conn()">登录聊天室</button>
</p>
<p><input type="text" id="content">
    <button onclick="send_msg()">发送消息</button>
</p>
<div id="message" style="width: 300px; border:2px solid red;">

</div>

</body>
<script type="text/javascript">
    var ws = null;
    var nickname = null;

    function create_conn() {
        nickname = document.getElementById("nickname").value;
        ws = new WebSocket("ws://192.168.15.108:9527/ws/" + nickname);
        ws.onopen = function () {
            alert("欢迎登陆九聊");
        };
        ws.onmessage = function (data) {
            var ws_msg = JSON.parse(data.data);
            create_chat(ws_msg);
        };
    }


    function create_chat(text, self) {
        var ptag = document.createElement("p");
        if (self == "w") {
            ptag.style.cssText = "text-align: right";
            ptag.innerText = text.msg + ":" + text.sender;
        } else {
            ptag.style.cssText = "text-align: left";
            ptag.innerText = text.sender + ":" + text.msg;
        }


        document.getElementById("message").appendChild(ptag);
    }

    function send_msg() {
        var msg = document.getElementById("content").value;
        // msg_json = JSON.stringify({"to_user":"","msg":msg});
        ws.send(msg_json);

        create_chat({sender:nickname,msg:msg}, "w");
    };


</script>
</html>

群聊flask代码

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

app = Flask(__name__)

user_socket_list = []
user_socket_dict = {}


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


@app.route("/ws/<nickname>")
def ws(nickname):
    user_socket = request.environ.get("wsgi.websocket")  # type: WebSocket
    # user_ip = request.environ.get("")
    print(nickname,":",request.environ.get("REMOTE_ADDR"))

    if user_socket:
        user_socket_dict[nickname] = user_socket

    print(len(user_socket_dict), user_socket_dict)
    while 1:
        msg = user_socket.receive()
        send_str = {"sender":nickname,"msg":msg}
        for nname,usocket in user_socket_dict.items():
            if usocket != user_socket:
                try:
                    usocket.send(json.dumps(send_str))
                except:
                    user_socket_dict.pop(nname)


# http://127.0.0.1:9527/ws
# websocket://127.0.0.1:9527/ws

if __name__ == '__main__':
    # app.run("0.0.0.0",9527,debug=True)

    http_serv = WSGIServer(("0.0.0.0", 9527), app, handler_class=WebSocketHandler)

    http_serv.serve_forever()
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p><input type="text" id="nickname">
    <button onclick="create_conn()">登录聊天室</button>
</p>
<p><input type="text" id="who">
    发送<input type="text" id="content">
    <button onclick="send_msg()">发送消息</button>
</p>
<div id="message" style="width: 300px; border:2px solid red;">

</div>

</body>
<script type="text/javascript">
    var ws = null;
    var nickname = null;

    function create_conn() {
        nickname = document.getElementById("nickname").value;
        ws = new WebSocket("ws://127.0.0.1:9527/ws/" + nickname);
        ws.onopen = function () {
            alert("欢迎登陆九聊");
        };
        ws.onmessage = function (data) {
            var ws_msg = JSON.parse(data.data);
            console.log(ws_msg);
            create_chat(ws_msg);
        };
    }


    function create_chat(text, self) {
        var ptag = document.createElement("p");
        if (self == "w") {
            ptag.style.cssText = "text-align: right";
            ptag.innerText = text.msg + ":" + text.sender;
        } else {
            ptag.style.cssText = "text-align: left";
            ptag.innerText = text.sender + ":" + text.msg;
        }
        document.getElementById("message").appendChild(ptag);
    }

    function send_msg() {
        var msg_str = document.getElementById("content").value;
        var who = document.getElementById("who").value;
        msg_json = JSON.stringify({"to_user":who,"msg":msg_str});
        ws.send(msg_json);

        create_chat({sender:nickname,msg:msg_str}, "w");
    };


</script>
</html>
私聊html
from flask import Flask, request, render_template
from geventwebsocket.websocket import WebSocket
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
import json

app = Flask(__name__)

user_socket_list = []
user_socket_dict = {}


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


@app.route("/ws/<nickname>")
def ws(nickname):
    user_socket = request.environ.get("wsgi.websocket")  # type: WebSocket
    # user_ip = request.environ.get("")
    print(nickname, ":", request.environ.get("REMOTE_ADDR"))

    if user_socket:
        user_socket_dict[nickname] = user_socket

    print(len(user_socket_dict), user_socket_dict)
    while 1:
        msg = user_socket.receive()
        msg_dict = json.loads(msg)
        print(msg_dict)
        # {msg : "FUCK" ,to_user:yinwangba}
        # send_str = {"sender": nickname, "msg": msg}

        # msg[to_user] = teacher
        usocket = user_socket_dict[msg_dict.get("to_user")]
        send_msg = json.dumps({"sender": nickname, "msg": msg_dict.get("msg")})
        usocket.send(send_msg)
        # dj = {sender:nickname,msg:"FUCK"}
        # usocket.send(dj)
        #----------------------------web端----------------------
        # {from_user:nickname,msg:"FUCK"}
        ####### {msg : "FUCK" ,to_user:yinwangba} ######
        # {msg : "FUCK too" ,to_user:nickname}



# http://127.0.0.1:9527/ws
# websocket://127.0.0.1:9527/ws

if __name__ == '__main__':
    # app.run("0.0.0.0",9527,debug=True)
    print('hhh')
    http_serv = WSGIServer(("127.0.0.1", 9527), app, handler_class=WebSocketHandler)

    http_serv.serve_forever()
私聊flask

 

posted @ 2018-11-01 15:04  luck_L  阅读(236)  评论(0编辑  收藏  举报