环境: django2.2.24 channels2.1.7 项目名mysite
注册channels
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app',
'channels',
]
配置ASGI_APPLICATION
ASGI_APPLICATION = 'mysite.routing.application'
mysite下创建routing.py文件
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
import app.routing
application = ProtocolTypeRouter({
'websocket': AuthMiddlewareStack(
URLRouter(app.routing.urlpatterns)
),
})
app下创建routing.py文件
from django.urls import path
from .consumers import Test
urlpatterns = [
path('ws/test', Test),
]
app下创建consumers.py文件
from channels.generic.websocket import WebsocketConsumer
class Test(WebsocketConsumer):
def connect(self):
self.accept()
print("连接来了")
for i in range(10):
self.send(str(i))
self.close()
def disconnect(self, code):
print("连接断开")
def receive(self, text_data=None, bytes_data=None):
print(text_data)
self.send(text_data)
===========================================
实现聊天
聊天实现需要用到Channels Layer redis做Channels Layer(官方推荐)
安装channels-redis
pip install channels_redis==2.3.3
在setting.py中添加配置
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": ["redis://:123456@127.0.0.1:6379/3"],
},
},
}
CHANNEL_LAYERS的其它配置配置方案 内存做channels layer
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels.layers.InMemoryChannelLayer",
}
}
consumers.py中的简单使用
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.room_name = "kuyer"
async_to_sync(self.channel_layer.group_add)(self.room_name, self.channel_name)
self.accept()
def disconnect(self, code):
async_to_sync(self.channel_layer.group_discard)(self.room_name, self.channel_name)
def receive(self, text_data=None, bytes_data=None):
async_to_sync(self.channel_layer.group_send)(
self.room_name,
{
'type': 'chat_message',
'message': text_data
}
)
def chat_message(self, event):
message = '微聊:' + event['message']
self.send(message)
|