Django實(shí)現(xiàn)WebSocket在線聊天室功能(channels庫(kù))
1.Django實(shí)現(xiàn)WebSocket在線聊天室
1.1 安裝
pip install channels==2.3
(saas) F:\Desktop\Python_Study\CHS-Tracer\saas>pip install channels==2.3
Looking in indexes: http://mirrors.aliyun.com/pypi/simple/
Collecting channels==2.3
Downloading
...
Successfully installed Automat-20.2.0 attrs-20.3.0 autobahn-21.3.1 channels-2.3.0
1.2 創(chuàng)建Django項(xiàng)目
1.3 http路由
url(r"^chat/$", chat_view.chat, name="chat"), # 聊天室
1.4 http視圖函數(shù)
def chat(request):
return render(request, "chat.html")
1.5 settings添加channels相關(guān)配置
INSTALLED_APPS = [
'channels', # 項(xiàng)目中要使用channels做WebSocket了
]
ASGI_APPLICATION = "saas.routing.application" # 項(xiàng)目名.routing.application
1.6 創(chuàng)建routing.py(websocket的路由)和comsumers.py(websocket的視圖函數(shù))


1.7 websocket路由
# -*- coding:utf-8 -*-
# 作者:IT小學(xué)生蔡坨坨
# 時(shí)間:2021/4/23 18:21
# 功能:channels相關(guān)路由
from channels.routing import ProtocolTypeRouter, URLRouter
from django.conf.urls import url
from web import consumers
application = ProtocolTypeRouter({
"websocket": URLRouter([
url(r'^chat/$', consumers.ChatConsumer),
])
})
1.8 websocket視圖函數(shù)
# -*- coding:utf-8 -*-
# 作者:IT小學(xué)生蔡坨坨
# 時(shí)間:2021/4/23 18:25
# 功能:channels相關(guān)視圖
from channels.exceptions import StopConsumer
from channels.generic.websocket import WebsocketConsumer
# 定義一個(gè)列表,用于存放當(dāng)前在線的用戶
CONSUMER_OBJECT_LIST = []
class ChatConsumer(WebsocketConsumer):
def websocket_connect(self, message):
"""
客戶端瀏覽器發(fā)來(lái)連接請(qǐng)求之后就會(huì)被觸發(fā)
:param message:
:return:
"""
# 服務(wù)端接收連接,向客戶端瀏覽器發(fā)送一個(gè)加密字符串
self.accept()
# 連接成功
CONSUMER_OBJECT_LIST.append(self)
def websocket_receive(self, message):
"""
客戶端瀏覽器向服務(wù)端發(fā)送消息,此方法自動(dòng)觸發(fā)
:param message:
:return:
"""
print("接受到消息了。", message)
# 服務(wù)端給客戶端回一條消息
# self.send(text_data=message["text"])
for obj in CONSUMER_OBJECT_LIST:
obj.send(text_data=message["text"])
def websocket_disconnect(self, message):
"""
客戶端瀏覽器主動(dòng)斷開(kāi)連接
:param message:
:return:
"""
# 服務(wù)端斷開(kāi)連接
CONSUMER_OBJECT_LIST.remove(self)
raise StopConsumer()
1.9 前端代碼
<!-- css樣式 -->
<style>
pre {
display: block;
padding: 9.5px;
margin: 0 0 10px;
font-size: 18px;
line-height: 1.42857143;
color: #333;
word-break: break-all;
word-wrap: break-word;
background-color: #00aaaa;
border-radius: 12px;
}
</style>
<!-- body內(nèi)容 -->
<div style="width: 600px;height: 574px;margin: auto;margin-top: 20px;">
<div class="panel panel-success">
<div class="panel-heading">在線實(shí)時(shí)聊天室</div>
<div class="panel-body">
<div style="border: #f5f5f5 2px solid;width: 570px;height: 400px;overflow:scroll">
<div id="content">
<!-- 聊天記錄 -->
</div>
</div>
<div style="border-color: white;margin-top: 10px">
<textarea type="text" id="txt" placeholder="請(qǐng)輸入消息內(nèi)容......" class="form-control"></textarea>
</div>
</div>
<div class="table">
<div>
<button class="btn btn-danger" onclick="closeLink();" style="margin-left: 74%">斷開(kāi)連接</button>
<button class="btn btn-success" onclick="sendMsg();">發(fā)送</button>
</div>
</div>
</div>
</div>
<!-- 消息模板 -->
<div id="recordTemplate" class="hide">
<div class="right-info">
<!-- 用戶 -->
<p>匿名用戶:</p>
<!-- 消息內(nèi)容 -->
<pre>
</pre>
</div>
</div>
<!-- js代碼 -->
<script>
var STATUS; // 是否連接的標(biāo)志
var ws = new WebSocket("ws://127.0.0.1:8000/chat/");
ws.onopen = function () {
// 客戶端在握手環(huán)節(jié)驗(yàn)證成功之后,自動(dòng)執(zhí)行此方法
console.log("連接成功。")
};
ws.onmessage = function msg(event) {
var $item = $("#recordTemplate").find('.right-info').clone();
$item.find('pre').html(event.data);
$("#content").append($item);
};
function sendMsg() {
if (STATUS == false) {
swal({
title: "已斷開(kāi)",
text: "當(dāng)前已斷開(kāi)連接,刷新頁(yè)面重新連接。"
});
} else {
ws.send($("#txt").val());
$("#txt").val("");
}
}
function closeLink() {
ws.close();
STATUS = false;
console.log("斷開(kāi)連接");
swal({
text: "成功斷開(kāi)連接,刷新頁(yè)面重新連接。"
});
}
</script>
2.效果展示

3.總結(jié)
http協(xié)議
chat路由 --> chat視圖函數(shù)
訪問(wèn):瀏覽器發(fā)送請(qǐng)求即可
websocket協(xié)議
chat路由 --> ChatConsumer(3個(gè)方法)
訪問(wèn):new WebSocket對(duì)象
到此這篇關(guān)于Django實(shí)現(xiàn)WebSocket在線聊天室(channels庫(kù))的文章就介紹到這了,更多相關(guān)Django實(shí)現(xiàn)WebSocket在線聊天室內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
yolov5訓(xùn)練時(shí)參數(shù)workers與batch-size的深入理解
最近再學(xué)習(xí)YOLOv3與YOLOv5訓(xùn)練數(shù)據(jù)集的具體步驟,幾經(jīng)波折終于實(shí)現(xiàn)了很好的效果,這篇文章主要給大家介紹了關(guān)于yolov5訓(xùn)練時(shí)參數(shù)workers與batch-size的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-03-03
Python函數(shù)中參數(shù)是傳遞值還是引用詳解
這篇文章主要介紹了深入了解Python函數(shù)中參數(shù)是傳值還是傳引用,在 C/C++ 中,傳值和傳引用是函數(shù)參數(shù)傳遞的兩種方式,在Python中參數(shù)是如何傳遞的,需要的朋友可以參考下2019-07-07
python之線程池map()方法傳遞多參數(shù)list
這篇文章主要介紹了python之線程池map()方法傳遞多參數(shù)list問(wèn)題,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
Python使用random模塊實(shí)現(xiàn)擲骰子游戲的示例代碼
這篇文章主要介紹了Python使用random模塊實(shí)現(xiàn)擲骰子游戲的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04

