简介
- channels2.0 可以让django具有处理http2,websocket的能力
相关库
- Python3.6
- Django 2.0
- pip install channels
- pip install channels_redis
配置settings.py
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
...
'channels',
)
ASGI_APPLICATION = "myproject.routing.application"
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("localhost", 6379)],
},
},
}
创建路由文件routing.py
from django.urls import path
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from .consumers import MyConsumer
application = ProtocolTypeRouter({
"websocket": AuthMiddlewareStack(
URLRouter([
path("chart/push", MyConsumer),
])
),
})
创建路由处理类文件consumers.py
from channels.generic.websocket import AsyncWebsocketConsumer
class MyConsumer(AsyncWebsocketConsumer):
async def connect(self):
await self.accept()
await self.channel_layer.group_add("chat", self.channel_name)
async def receive(self, text_data=None, bytes_data=None):
await self.channel_layer.group_send(
"chat",
{
"type": "chat.message",
"text": "Hello world!",
},
)
async def disconnect(self, close_code):
await self.channel_layer.group_discard("chat", self.channel_name)
await self.close()
async def chat_message(self, event):
await self.send(text_data=event["text"])
启动Django
python manage.py runserver 0.0.0.0:8080
测试HTML
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Django websocket</title>
<script type="text/javascript">
function WebSocketTest()
{
if ("WebSocket" in window)
{
alert("您的浏览器支持 WebSocket!");
var ws = new WebSocket("ws://localhost:8080/chart/push");
ws.onopen = function()
{
alert("数据发送中...");
ws.send("hello world")
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
console.log(received_msg)
};
ws.onclose = function()
{
alert("连接已关闭...");
};
}
else
{
alert("您的浏览器不支持 WebSocket!");
}
}
</script>
</head>
<body>
<div id="sse">
<a href="javascript:WebSocketTest()">运行 WebSocket</a>
</div>
</body>
</html>
效果
- 连接成功时,Django会输出状态,handshaking -> connect
- 点击连接后,在console会输出hello world