群聊版 安裝 pipinstallgevent-websocket 視圖 #-*-coding:utf-8-*- importjson fromflaskimportFlask,request,render_template fromgeventwebsocket.handlerimportWebS... ...
群聊版
安裝
pip install gevent-websocket
視圖
- # -*- coding: utf-8 -*-
- import json
- from flask import Flask, request, render_template
- from geventwebsocket.handler import WebSocketHandler # 導入websocker的方法
- from gevent.pywsgi import WSGIServer
- app = Flask(__name__)
- user_socker_list = [] # 保存所有的websocker對象
- @app.route('/ws')
- def ws():
- # print(request.headers)
- user_socker = request.environ.get('wsgi.websocket') # type WebSocket
- """
- readyState: 3 連接正常,然後斷開
- readyState: 1 表示正常連接
- """
- if user_socker:
- user_socker_list.append(user_socker)
- while 1:
- msg = user_socker.receive() # 接收消息
- print(msg) # 接受完信息後斷開,所有加迴圈變成長連接
- for u_socker in user_socker_list:
- if u_socker == user_socker:
- continue
- try:
- u_socker.send(msg)
- except:
- continue
- return render_template('ws.html')
- if __name__ == '__main__':
- # app.run(host='0.0.0.', debug=True)
- http_serv = WSGIServer(('0.0.0.0', 5000), app, handler_class=WebSocketHandler)
- http_serv.serve_forever()
前端
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>ws</title>
- </head>
- <body>
- <input type="text" id="msg"> <button onclick="snd_msm()">發送</button>
- <div id="chat_list" style="width: 500px; height: 500px;">
- </div>
- </body>
- <script type="application/javascript">
- var ws = new WebSocket('ws://192.168.32.71:5000/ws'); {# 設置websocker連接 #}
- ws.onmessage = function (data) {
- console.log(data.data); {# 數據在data。data裡面 #}
- var ptag = document.createElement('p');
- ptag.innerText = data.data;
- document.getElementById('chat_list').appendChild(ptag)
- }; {# 列印收到的數據 #}
- function snd_msm() {
- var msg = document.getElementById('msg').value;
- ws.send(msg)
- }
- </script>
- </html>
一對一單機版
視圖
- # -*- coding: utf-8 -*-
- import json
- from flask import Flask, request, render_template
- from geventwebsocket.handler import WebSocketHandler # 導入websocker的方法
- from gevent.pywsgi import WSGIServer
- app = Flask(__name__)
- user_socker_dict = {} # 這裡仿照flask上下文的方式
- """
- 借用
- flask 上下文
- {
- "線程id": 偏函數,
- "線程id": 偏函數,
- }
- """
- @app.route('/ws2/<usename>')
- def ws2(usename):
- # print(request.headers)
- user_socker = request.environ.get('wsgi.websocket') # type WebSocket
- """
- readyState: 3 連接正常,然後斷開
- readyState: 1 表示正常連接
- """
- print(user_socker)
- if user_socker:
- user_socker_dict[usename] = user_socker
- print(user_socker_dict)
- while 1:
- msg = user_socker.receive() # 接收人,消息,發送人
- msg_dict = json.loads(msg)
- msg_dict['from_user'] = usename
- to_user = msg_dict.get('to_user')
- u_socker = user_socker_dict.get(to_user) # type WebSocket
- u_socker.send(json.dumps(msg_dict))
- return render_template('ws2.html')
- if __name__ == '__main__':
- # app.run(host='0.0.0.', debug=True)
- http_serv = WSGIServer(('0.0.0.0', 5000), app, handler_class=WebSocketHandler)
- http_serv.serve_forever()
前端
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>ws</title>
- </head>
- <body>
- <input type="text" id="username"> <button onclick="login()">登陸聊天室</button>
- 給<input type="text" id="to_user">發送:<input type="text" id="msg"> <button onclick="snd_msm()">發送</button>
- <div id="chat_list" style="width: 500px; height: 500px;">
- </div>
- </body>
- <script type="application/javascript">
- var ws = null; {# 為什麼設置null, 被其他函數執行 #}
- function login() {
- var username = document.getElementById('username').value;
- ws = new WebSocket('ws://192.168.32.71:5000/ws2/' + username); {# 設置websocker連接 #}
- ws.onmessage = function (data) {
- var recv_msg = JSON.parse(data.data);
- var ptag = document.createElement('p');
- ptag.innerText = recv_msg.from_user + ":" + recv_msg.msg;
- document.getElementById('chat_list').appendChild(ptag)
- }; {# 列印收到的數據 #}
- }
- function snd_msm() {
- var to_user = document.getElementById('to_user').value;
- var msg = document.getElementById('msg').value;
- send_msg = {
- "to_user" : to_user,
- "msg": msg
- };
- ws.send(JSON.stringify(send_msg));
- }
- </script>
- </html>
Websocker
視圖
- import time
- from django.shortcuts import render
- from dwebsocket.decorators import accept_websocket
- @accept_websocket
- def test(request):
- if request.is_websocket():
- print('websocket connection....')
- msg = request.websocket.wait() # 接收前端發來的消息
- print(msg, type(msg), json.loads(msg)) # b'["1","2","3"]' <class 'bytes'> ['1', '2', '3']
- while 1:
- if msg:
- # 你要返回的結果
- for i in range(10):
- request.websocket.send(str(i).encode()) # 向客戶端發送數據
- request.websocket.close()
- else: # 如果是普通的請求返回頁面
- return render(request, 'test.html')
前端
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="x-ua-compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <title>test</title>
- </head>
- <body>
- <div></div>
- </body>
- <input type="text" id="message" value="Hello, World!"/>
- <button type="button" id="send_message">發送 message</button>
- <!-- 首先引入 jQuery -->
- <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
- <script>
- // 判斷瀏覽器是否支持WebSocket,目前應該所有的瀏覽器都支持了.....
- if ('WebSocket' in window) {
- console.log('你的瀏覽器支持 WebSocket')
- }
- $('#send_message').click(function () {
- // 創建一個WebSocket對象:sk,並且建立與服務端的連接(服務端程式要跑著哦)
- var sk = new WebSocket('ws://' + window.location.host + '/asset/test/');
- // 向服務端發送消息
- sk.onopen = function () {
- console.log('websocket connection successful...');
- var datas = $('#message').val();
- sk.send(JSON.stringify(datas));
- };
- // 接收服務端的消息,主要的業務邏輯也在這裡完成
- sk.onmessage = function (msg) {
- // 業務邏輯
- html = "<p>" + msg.data + "</p>";
- $("div").append(html);
- console.log('from service message: ', msg.data);
- // 由於服務端主動斷開連接,這裡也斷開WebSocket連接
- if (sk.readyState == WebSocket.CLOSED) sk.close();
- };
- // 完事就關閉WebSocket連接
- sk.onclose = function (msg) {
- console.log('websocket connection close...');
- sk.close()
- };
- // 當WebSocket連接創建成功後,我們就可以向服務端發送數據了
- if (sk.readyState == WebSocket.OPEN) sk.onopen();
- });
- </script>
- </html>