python本身只支持http协议 使用websocket需要下载第三方库
pip install -U channels
需要在seting.py里配置,将我们的channels加入INSTALLED_APP里。
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
...
'channels',
)
尾行添加
ASGI_APPLICATION = 'bug_Project_name.asgi.application'
修改asgi.py文件
import os
from channels.routing import ProtocolTypeRouter,URLRouter
from django.core.asgi import get_asgi_application
from . import routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bug_Project2.settings')
#application = get_asgi_application()
application = ProtocolTypeRouter({
"http":get_asgi_application(),
"websockt":URLRouter(routing.websoctet_urlpatterns )
})
在settings.py的同级目录创建routing.py
from django.urls import re_path
from web import consumerswebsoctet_urlpatterns = [
re_path('ws/(?P<group>\w+)/$',consumers.ChatConsumer.as_asgi()),
]
在web.views中创建consumers.py
# -*- coding:UTF-8 -*-
# author:Administrator
# contact: 913632472@qq.com
# datetime:2022/1/10 11:55
# software: PyCharm"""
文件说明:
"""from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumerclass ChatConsumer(WebsocketConsumer):
def websocket_connect(self,message):
# 有客户端来向后端发送websocket连接请求时,自动触发
# 后端允许客户端创建连接
print('有人来了')
self.accept()
#给客户端发送小时
self.send("欢迎啊")def websocket_receive(self, message):
# 浏览器基于websocket向后端发送数据,自动触发接受消息
text = message['text']
print("接受到消息-->", text)
res = "{}SB".format(text)
if text == "关闭":
# 客户端通过发送命令 主动断开连接
self.close()
print('通过命令关闭')
raise StopConsumer # 如果服务端断开连接,执行StopConsumer异常 那么websocket_disconnect不会执行
self.send(res)
# self.close() #后端主动断开websocket
def websocket_disconnect(self, message):
# 客户端与服务端断开连接,自动触发
print("客户端断开连接")
raise StopConsumer
django中需要了解的
- wsgi,只支持http请求
- asgi,wsgi+异步+websockt
settings.py的installed_apps中的首行
简单使用前端页面测试websocket
<html lang="en">
<head>
<meta charset="UTF-16">
<title>title</title>
<style>
.message{
height: 300px;
border: 1px solid #dddddd;
width: 100%;
}
</style>
</head>
</html>
<div class="message" id="message"></div>
<div>
<input type="text" placeholder="请输入" id="txt">
<input type="button" value="发送" οnclick="sendMessage()">
</div><script>
socket = new WebSocket("ws://127.0.0.1:8000/room/123/")
//创建好连接后触发
socket.onopen = function (event) {
let tag = document.createElement("div");
tag.innerText = "[连接成功]";
document.getElementById("message").appendChild(tag);}
//当websocket接受要服务端发来的信息 会自动触发这个函数
socket.onmessage = function (event){
let tag = document.createElement("div");
tag.innerText = event.data;
document.getElementById("message").appendChild(tag);
}function sendMessage(){
let tag = document.getElementById("txt");
socket.send(tag.value);
}function closeConn() {
socket.close(); //服务端发送断开请求}
</script>
遇到问题
websocket介绍:
channels 4.0之后默认不带Daphne服务器了。
解决方案可以有两种:
1.指定channels的版本为3.x;
2.安装时使用pip3 install -U channels[“daphne”]
【全网最详细Django的websocket 通信原理,聊天室,实战案例-哔哩哔哩】http:// https://b23.tv/os2enKj
参考链接http://t.csdn.cn/RyrcC
备用链接django中配置websocket_基于wsgi创建的项目怎么实现websocket_qq_36606793的博客-CSDN博客