9.channels layers
settings.py配置
# 存储在内存里
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels.layers.InMemoryChannelLayer",
}
}
# 存储在redis
安装:pip3 install channels-redis
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG":{
"hosts":['10.211.55.25',6379]
}
}}
channel_layer使用
连接
#异步连接
def websocket_connect(self, message):
# 将这个客户端的连接对象加入到某个地方(内存 or redis)
# channel_name 代表当前客户端连接创建到别名,放到名称A的组里
# 这种写法默认是异步的
self.channel_layer.grouo_add('名称A',self.channel_name)
# 如果不需要异步 ,没有写异步代码的话,我们可以将异步改为同步
from asgiref.sync import async_to_sync
def websocket_connect(self, message):
async_to_sync(self.channel_layer.grouo_add)('名称A',self.channel_name)
发送消息
#发送消息
def receive(self, text_data=None, bytes_data=None):
# 直接调用send,是给当前单个用户发送消息
self.send('1')
# 向名称A组内所有用户发送消息
async_to_sync(self.channel_layer.group_send)('名称A', {'messgae': '消息'})
#发送消息执行方法
def receive(self, text_data=None, bytes_data=None):
# 通知组内所有的客户端,执行ws_func方法,方法内可以自定义功能
async_to_sync(self.channel_layer.group_send)('名称A', {'type': 'ws_func','message':'消息'})
def ws_func(self,event):
# 向组内的每个用户发送消息
text = event['message']
self.send(text)
断开链接
def websocket_disconnect(self, message):
# 将当前用户从名称A的组内移除
async_to_sync(self.channel_layer.group_discard)('名称A',self.channel_name)_
raise StopConsumer()
动态获取路由匹配分组
# 路由
re_path(r'room/(?P<group>\w+)/$',Consumer)
def websocket_connect(self, message):
group = self.scope['url_route']['kwargs'].get('group')
async_to_sync(self.channel_layer.grouo_add)(group, self.channel_name)
风月都好看,人间也浪漫.