ws目录
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/14902173191c7b62797e785e438fd7d2.png)
第三方包安装
pip install channels
pip install channels_redis
主目录settings文件配置
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'index',
'djcelery',
'app01',
"channels",
'wsocket'
]
ASGI_APPLICATION = "BookStore.routing.application"
主目录新增routing.py文件
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import wsocket.routing
application = ProtocolTypeRouter({
"websocket": AuthMiddlewareStack(
URLRouter(
wsocket.routing.websocket_urlpatterns
)
),
})
新增wscoket–app并注册app到setting中
django-admin startapp wscoket
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0fda12573f4114ca1843eed9691a3996.png)
wsocket目录操作
新增routing.py和conView.py
from django.conf.urls import url
from wsocket.conView import ChatService
websocket_urlpatterns = [
url(r"ws/", ChatService()),
]
import json
import time
from channels.generic.websocket import WebsocketConsumer
class ChatService(WebsocketConsumer):
def connect(self):
print("已连接")
self.accept()
for i in range(10):
time.sleep(2)
self.send(text_data=json.dumps({
'code': 200,
'message': "djhafkja"
}))
def receive(self, text_data=None, bytes_data=None):
print("已收到消息")
def disconnect(self, code):
print("已断开")
启动程序
python manager.py runserver 8000
接口测试代码client
import asyncio
import websockets
async def hello():
uri = "ws://127.0.0.1:8000/ws/"
async with websockets.connect(uri) as websocket:
while True:
data = await websocket.recv()
print(data)
asyncio.get_event_loop().run_until_complete(hello())
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7d1acdabed7c01cbc6927b3259bd8d53.png)