django channels使用和配置及實現(xiàn)群聊
1.1WebSocket原理
http協(xié)議
- 連接
- 數(shù)據(jù)傳輸
- 斷開連接
websocket協(xié)議,是建立在http協(xié)議之上的。
- 連接,客戶端發(fā)起。
- 握手(驗證),客戶端發(fā)送一個消息,后端接收到消息再做一些特殊處理并返回。 服務端支持websocket協(xié)議。
1.2django框架
django默認不支持websocket,需要安裝組件:
pip install channels
配置:
注冊channels
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', ]
在settings.py中添加 asgi_application
ASGI_APPLICATION = "ws_demo.asgi.application"
修改asgi.py文件
import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from . import routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ws_demo.settings') # application = get_asgi_application() application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter(routing.websocket_urlpatterns), })
在settings.py的同級目錄創(chuàng)建 routing.py
from django.urls import re_path from app01 import consumers websocket_urlpatterns = [ re_path(r'ws/(?P<group>\w+)/$', consumers.ChatConsumer.as_asgi()), ]
在app01目錄下創(chuàng)建 consumers.py,編寫處理處理websocket的業(yè)務邏輯。
from channels.generic.websocket import WebsocketConsumer from channels.exceptions import StopConsumer class ChatConsumer(WebsocketConsumer): def websocket_connect(self, message): # 有客戶端來向后端發(fā)送websocket連接的請求時,自動觸發(fā)。 # 服務端允許和客戶端創(chuàng)建連接。 self.accept() def websocket_receive(self, message): # 瀏覽器基于websocket向后端發(fā)送數(shù)據(jù),自動觸發(fā)接收消息。 print(message) self.send("不要回復不要回復") # self.close() def websocket_disconnect(self, message): # 客戶端與服務端斷開連接時,自動觸發(fā)。 print("斷開連接") raise StopConsumer()
小結
基于django實現(xiàn)websocket請求,但現(xiàn)在為止只能對某個人進行處理。
2.0 實現(xiàn)群聊
2.1 群聊(一)
前端:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .message { height: 300px; border: 1px solid #dddddd; width: 100%; } </style> </head> <body> <div class="message" id="message"></div> <div> <input type="text" placeholder="請輸入" id="txt"> <input type="button" value="發(fā)送" onclick="sendMessage()"> <input type="button" value="關閉連接" onclick="closeConn()"> </div> <script> socket = new WebSocket("ws://127.0.0.1:8000/room/123/"); // 創(chuàng)建好連接之后自動觸發(fā)( 服務端執(zhí)行self.accept() ) socket.onopen = function (event) { let tag = document.createElement("div"); tag.innerText = "[連接成功]"; document.getElementById("message").appendChild(tag); } // 當websocket接收到服務端發(fā)來的消息時,自動會觸發(fā)這個函數(shù)。 socket.onmessage = function (event) { let tag = document.createElement("div"); tag.innerText = event.data; document.getElementById("message").appendChild(tag); } // 服務端主動斷開連接時,這個方法也被觸發(fā)。 socket.onclose = function (event) { let tag = document.createElement("div"); tag.innerText = "[斷開連接]"; document.getElementById("message").appendChild(tag); } function sendMessage() { let tag = document.getElementById("txt"); socket.send(tag.value); } function closeConn() { socket.close(); // 向服務端發(fā)送斷開連接的請求 } </script> </body> </html>
后端:
from channels.generic.websocket import WebsocketConsumer from channels.exceptions import StopConsumer CONN_LIST = [] class ChatConsumer(WebsocketConsumer): def websocket_connect(self, message): print("有人來連接了...") # 有客戶端來向后端發(fā)送websocket連接的請求時,自動觸發(fā)。 # 服務端允許和客戶端創(chuàng)建連接(握手)。 self.accept() CONN_LIST.append(self) def websocket_receive(self, message): # 瀏覽器基于websocket向后端發(fā)送數(shù)據(jù),自動觸發(fā)接收消息。 text = message['text'] # {'type': 'websocket.receive', 'text': '阿斯蒂芬'} print("接收到消息-->", text) res = "{}SB".format(text) for conn in CONN_LIST: conn.send(res) def websocket_disconnect(self, message): CONN_LIST.remove(self) raise StopConsumer()
2.2 群聊(二)
第二種實現(xiàn)方式是基于channels中提供channel layers來實現(xiàn)。(如果覺得復雜可以采用第一種)
setting中配置 。
CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer", } }
如果是使用的redis 環(huán)境
pip3 install channels-redis
CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [('10.211.55.25', 6379)] }, }, }
consumers中特殊的代碼。
from channels.generic.websocket import WebsocketConsumer from channels.exceptions import StopConsumer from asgiref.sync import async_to_sync class ChatConsumer(WebsocketConsumer): def websocket_connect(self, message): # 接收這個客戶端的連接 self.accept() # 將這個客戶端的連接對象加入到某個地方(內(nèi)存 or redis)1314 是群號這里寫死了 async_to_sync(self.channel_layer.group_add)('1314', self.channel_name) def websocket_receive(self, message): # 通知組內(nèi)的所有客戶端,執(zhí)行 xx_oo 方法,在此方法中自己可以去定義任意的功能。 async_to_sync(self.channel_layer.group_send)('1314', {"type": "xx.oo", 'message': message}) #這個方法對應上面的type,意為向1314組中的所有對象發(fā)送信息 def xx_oo(self, event): text = event['message']['text'] self.send(text) def websocket_disconnect(self, message): #斷開鏈接要將這個對象從 channel_layer 中移除 async_to_sync(self.channel_layer.group_discard)('1314', self.channel_name) raise StopConsumer()
好了分享就結束了,其實總的來講介紹的還是比較淺
如果想要深入一點 推薦兩篇博客
【翻譯】Django Channels 官方文檔 -- Tutorial - 守護窗明守護愛 - 博客園
到此這篇關于django channels使用和配置及實現(xiàn)群聊的文章就介紹到這了,更多相關django channels配置內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python基于Pandas讀寫MySQL數(shù)據(jù)庫
這篇文章主要介紹了python基于Pandas讀寫MySQL數(shù)據(jù)庫,幫助大家更好的理解和學習使用python,感興趣的朋友可以了解下2021-04-0410個python3常用排序算法詳細說明與實例(快速排序,冒泡排序,桶排序,基數(shù)排序,堆排序,希爾排序,歸并排序,計數(shù)排
這篇文章主要介紹了10個python3常用排序算法詳細說明與實例,需要的朋友可以參考下2020-03-03