Flask實現簡單的群聊和單聊


    Flask是使用python寫的一個簡單輕量級的框架,今天我們使用Flask實現一個簡單的單聊和群聊功能 .

                                              

    主要思路 : 前端登錄聊天室,聊天室信息包含用戶的登錄信息,相當於一個登錄功能,會把這個信息記錄在url中發送給后端,后端會把登錄信息作為識別用戶的標志,url中的信息會作為key值存在一個字典中:

    {'111': <geventwebsocket.websocket.WebSocket object at 0x000001AB31716118>, '222': <geventwebsocket.websocket.WebSocket object at 0x000001AB317160B0>}

    單聊也是基於這個key值實現的,如果發送的用戶為空則默認為群聊;

 

一.導入相關的包並實例化一個Flask對象

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__)    #實例化一個Flask對象
user_socket_dict = {}    #創建一個空字典

二.后端通過request.environ獲取前端的所有信息,其中wsgi.websocket對應的值即用戶對象,取出這個對象存入字典 :

@app.route('/ws_app/<user_nick>')     #設置Flask路由,前端通過訪問這個地址拆解信息,<user_nick>即前端登錄聊天室輸入的內容
def ws_app(user_nick):
    user_socket = request.environ.get("wsgi.websocket")  # type:WebSocket    #取出environ中的wsgi.websocket對應的值
    user_socket_dict[user_nick] = user_socket         #以<user_nick>為key在字典中插入用戶信息
print(user_socket_dict)     #{'111': <geventwebsocket.websocket.WebSocket object at 0x000001AB31716118>, '222': <geventwebsocket.websocket.WebSocket object at 0x000001AB317160B0>}

三.通過receive取出用戶要發送的內容並進行json轉換,通過get方法取出to_user(要發送的對象的聊天號),如果沒有返回0,后邊再通過if判斷區別單聊還是群聊:如果to_user存在,說明要發給單個用戶,否則是群發. 

    while True:
        msg = user_socket.receive()           #取出發送內容
        
        msg_dict = json.loads(msg)
        to_user = msg_dict.get("to_user",0)   #沒有返回0
        if to_user:                           #有發送對象   單聊
            to_user_socket = user_socket_dict.get(to_user)    #用get方法取出
            to_user_socket.send(msg)
        else:                                  #沒有發送對象    群聊
            for usocket in list(user_socket_dict.values()):
                usocket.send(msg)
    
    @app.route('/')
    def index():
      return render_template('my_ws.html')


if __name__ == '__main__':
    http_serve = WSGIServer(('0.0.0.0', 9527), app, handler_class=WebSocketHandler)
    http_serve.serve_forever() 

四.前端代碼

 1 <body>
 2 <p><input type="text" id="nick">
 3     <button onclick="login()">登陸聊天室</button>
 4 </p>
 5 發送給:<input type="text" id="to_user">消息:<input type="text" id="send_str">
 6 <button id="send_btn" onclick="send()">發送消息</button>
 7 <p>
 8 <div id="chat_list">
 9 
10 </div>
11 </p>
12 </body>
13 <script type="application/javascript">
14     var ws = null;
15     function login() {
16         var nick = document.getElementById("nick").value;
17         ws = new WebSocket("ws://192.168.***.***:9527/ws_app/" + nick);
18         ws.onmessage = function (messageEvent) {
19             console.log(messageEvent.data);
20             var ptag = document.createElement("p");
21 
22             var message = JSON.parse(messageEvent.data);
23 
24             ptag.innerText = message.from_user + " : " + message.message;
25             document.getElementById("chat_list").appendChild(ptag);
26         };
27     }
28 
29     function send() {
30         var message = document.getElementById("send_str").value;
31         var send_str = {
32             from_user: document.getElementById("nick").value,
33             to_user: document.getElementById("to_user").value,
34             message: message
35         };
36         var json_send_str = JSON.stringify(send_str);
37         ws.send(json_send_str);
38     }
39 </script>
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM