Websocket是一种用于H5浏览器的实时通讯协议,可以做到数据的实时推送,可适用于广泛的工作环境,例如客服系统、物联网数据传输系统。
常见的案例:在点餐系统中,当用户完成下单后,可以实时通知单到服务员;你猜我画的小游戏中,玩家可以实时看到对方在画的内容,也是通过Websocket进行通讯。
下面的案例是使用Django框架配合channels库实现Websocket。
Channels 包装了 Django 的原生异步视图支持,允许 Django 项目不仅处理 HTTP,还处理需要长时间运行连接的协议 - WebSockets、MQTT、聊天机器人。
1.创建django项目
django-admin startproject mysite
2.进入mysite目录,创建应用程序
django-admin startapp chat
3.安装依赖包
pip install channels
pip install channels_redis
4.在setting.py中配置
INSTALLED_APPS = [
'chat',
'channels',
]
5.在chat目录新建consumers.py
import json
from channels.generic.websocket import AsyncWebsocketConsumer
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name
# Join room group
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
# Leave room group
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
# Receive message from WebSocket
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
# Send message to room group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message
}
)
# Receive message from room group
async def chat_message(self, event):
message = event['message']
# Send message to WebSocket
await self.send(text_data=json.dumps({
'message': message
}))
6.在mysit(wsgi.py同级目录)中新建asgi.py
import os
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.urls import re_path
from chat.consumers import ChatConsumer
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
application = ProtocolTypeRouter({
"websocket": AuthMiddlewareStack(
URLRouter(
[re_path(r'chat/(?P<room_name>\w+)/$', ChatConsumer.as_asgi()),]
)
),
})
7.在setting.py中设置
ASGI_APPLICATION = 'mysite.asgi.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": ["redis://127.0.0.1:6379/0"],
},
},
}
8.部署服务器
安装:pip install daphne
运行:daphne -p 8001 mysite.asgi:application #指定运行的端口号
9.连接测试

原创文章,作者:Rosmontis,如若转载,请注明出处:https://rosmontis.com/archives/179