1、安装指定版本的包
pip install channels==3.0.4
pip install channels_redis
2.settings里配置
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'channels',]
WSGI_APPLICATION = 'Dating_Sofware.wsgi.application' #Dating_Sofware项目名称
ASGI_APPLICATION = "Dating_Sofware.asgi.application"CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
3.在项目根目录下创建asgi.py内容如下:
import os
import django
from channels.http import AsgiHandler
from channels.routing import ProtocolTypeRouter, URLRouter
from . import routings # 这个文件后续会说,你先写上。
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Dating_Sofware.settings')#Dating_Sofware 是项目名称
django.setup()
application = ProtocolTypeRouter(
{
"http": AsgiHandler(), # http走Django默认的asgi
"websocket": URLRouter(routings.websocket_urlpatterns), # websocket走channels
}
)
4.同根目录下创建consumers.py内容如下:
import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
CONN_LIST = []
class ChatConsumer(WebsocketConsumer):
def websocket_connect(self, message):
print("开始链接...")
# 有客户端来向后端发送websocket连接的请求时,自动触发。
# 服务端允许和客户端创建连接(握手)。
self.accept()
CONN_LIST.append(self)
def websocket_receive(self, message):
print('22222222', message)
data = json.loads(message.get('text', '{}'))
chat_type = data.get('chat_type')
chat_id = data.get('chat_id')
chat_content = data.get('message')
if chat_type == 'add_chat':
async_to_sync(self.channel_layer.group_add)(chat_id, self.channel_name)
else:
async_to_sync(self.channel_layer.group_send)(chat_id, {"type": 'chat.message', 'message': message})
def chat_message(self, event):
self.send(event['message']['text'])
def websocket_disconnect(self, message):
CONN_LIST.remove(self)
raise StopConsumer()
5.项目根目录下创建routings.py
from django.urls import path
from Dating_Sofware.consumers import ChatConsumer #Dating_Sofware是创建的项目名。consumers是上面创建的consumers.py
websocket_urlpatterns = [
path('ws/chat', ChatConsumer.as_asgi()),
]
6.运行项目出现如下内容即可
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
June 22, 2022 - 19:19:44
Django version 2.2.2, using settings 'Dating_Sofware.settings'
Starting ASGI/Channels version 3.0.4 development server at http://127.0.0.1:8000/ 出现ASGI算完成
Quit the server with CTRL-BREAK.