基于flask 写的web_socket 单聊和群聊

Posted awfj

tags:

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

群聊

 

技术图片
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)

    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)

        # user_socket.send(msg)

    # 1 已经开启的websocket连接
    # 3 开启了websocket连接 然后 断开了


    # return "666"


@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()
群聊

 

技术图片
<!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.182: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>
群聊前端代码

单聊

 

技术图片
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):
    # print(request.environ)
    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()
        # {from_user:"alexDSB",to_user:"YWB",message:"666"}
        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)


    # 1 已经开启的websocket连接
    # 3 开启了websocket连接 然后 断开了





@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()
单聊

 

技术图片
<!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.182: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>
单聊前端代码

 

以上是关于基于flask 写的web_socket 单聊和群聊的主要内容,如果未能解决你的问题,请参考以下文章

Netty网络聊天 聊天室实战

微信聊天的长连设计探讨之负载均衡

使用Nio实现一个简易的群聊和单聊

javascript基于websocketnodejsuniapp的聊天室

javascript基于websocketnodejsuniapp的聊天室

python-flask复习——- flask请求上下文源码解读http聊天室单聊/群聊(基于gevent-websocket)