溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

django?channels使用、配置及實(shí)現(xiàn)群聊的方法

發(fā)布時間:2022-05-31 13:52:08 來源:億速云 閱讀:160 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“django channels使用、配置及實(shí)現(xiàn)群聊的方法”,在日常操作中,相信很多人在django channels使用、配置及實(shí)現(xiàn)群聊的方法問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”django channels使用、配置及實(shí)現(xiàn)群聊的方法”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

1.1WebSocket原理

http協(xié)議

  • 連接

  • 數(shù)據(jù)傳輸

  • 斷開連接

websocket協(xié)議,是建立在http協(xié)議之上的。

  • 連接,客戶端發(fā)起。

  • 握手(驗(yàn)證),客戶端發(fā)送一個消息,后端接收到消息再做一些特殊處理并返回。 服務(wù)端支持websocket協(xié)議。

1.2django框架

django默認(rèn)不支持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è)務(wù)邏輯。

from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
 
 
class ChatConsumer(WebsocketConsumer):
    def websocket_connect(self, message):
        # 有客戶端來向后端發(fā)送websocket連接的請求時,自動觸發(fā)。
        # 服務(wù)端允許和客戶端創(chuàng)建連接。
        self.accept()
 
    def websocket_receive(self, message):
        # 瀏覽器基于websocket向后端發(fā)送數(shù)據(jù),自動觸發(fā)接收消息。
        print(message)
        self.send("不要回復(fù)不要回復(fù)")
        # self.close()
 
    def websocket_disconnect(self, message):
        # 客戶端與服務(wù)端斷開連接時,自動觸發(fā)。
        print("斷開連接")
        raise StopConsumer()

小結(jié)

基于django實(shí)現(xiàn)websocket請求,但現(xiàn)在為止只能對某個人進(jìn)行處理。

2.0 實(shí)現(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="關(guān)閉連接" onclick="closeConn()">
</div>
 
<script>
 
    socket = new WebSocket("ws://127.0.0.1:8000/room/123/");
 
    // 創(chuàng)建好連接之后自動觸發(fā)( 服務(wù)端執(zhí)行self.accept() )
    socket.onopen = function (event) {
        let tag = document.createElement("div");
        tag.innerText = "[連接成功]";
        document.getElementById("message").appendChild(tag);
    }
 
    // 當(dāng)websocket接收到服務(wù)端發(fā)來的消息時,自動會觸發(fā)這個函數(shù)。
    socket.onmessage = function (event) {
        let tag = document.createElement("div");
        tag.innerText = event.data;
        document.getElementById("message").appendChild(tag);
    }
 
    // 服務(wù)端主動斷開連接時,這個方法也被觸發(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(); // 向服務(wù)端發(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ā)。
        # 服務(wù)端允許和客戶端創(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 群聊(二)

第二種實(shí)現(xiàn)方式是基于channels中提供channel layers來實(shí)現(xiàn)。(如果覺得復(fù)雜可以采用第一種)

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})
 
        #這個方法對應(yīng)上面的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()

到此,關(guān)于“django channels使用、配置及實(shí)現(xiàn)群聊的方法”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI