feat: 添加websocket模块

This commit is contained in:
caoqianming 2023-09-01 09:12:18 +08:00
parent d5386ccd84
commit 8e0724bbec
10 changed files with 105 additions and 4 deletions

0
apps/ws/__init__.py Normal file
View File

3
apps/ws/admin.py Normal file
View File

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

6
apps/ws/apps.py Normal file
View File

@ -0,0 +1,6 @@
from django.apps import AppConfig
class WsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'ws'

74
apps/ws/consumers.py Normal file
View File

@ -0,0 +1,74 @@
from channels.generic.websocket import AsyncWebsocketConsumer
import json
class RoomConsumer(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
)
username = self.scope['user'].username
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat',
'msg': f'你好,{username}, 欢迎进入{self.room_name}房间' ,
'from': '系统',
'to': username
}
)
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
)
async def receive_json(self, content, **kwargs):
sender_user = self.scope["user"]
if content['type'] == 'chat':
content['from'] = sender_user.username
await self.channel_layer.group_send(
self.room_group_name,
content
)
async def chat(self, content):
await self.send(json.dumps(content, ensure_ascii=False))
class MyConsumer(AsyncWebsocketConsumer):
async def connect(self):
user_id = self.scope['user'].id
self.room_group_name = f'user_{user_id}'
# Join room group
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'event',
'msg': '你好,' + self.scope['user'].username,
'from': '系统'
}
)
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
)
async def event(self, content):
await self.send(json.dumps(content, ensure_ascii=False))

View File

3
apps/ws/models.py Normal file
View File

@ -0,0 +1,3 @@
from django.db import models
# Create your models here.

9
apps/ws/routing.py Normal file
View File

@ -0,0 +1,9 @@
from django.urls import path
from apps.ws.consumers import MyConsumer, RoomConsumer
WS_BASE_URL = 'ws/'
websocket_urlpatterns = [
path(f'{WS_BASE_URL}my/', MyConsumer.as_asgi()),
path(WS_BASE_URL + '<str:room_name>/', RoomConsumer.as_asgi()),
]

3
apps/ws/tests.py Normal file
View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

3
apps/ws/views.py Normal file
View File

@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.

View File

@ -10,16 +10,16 @@ https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
import os import os
from channels.routing import ProtocolTypeRouter, URLRouter from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application from django.core.asgi import get_asgi_application
from channels.auth import AuthMiddlewareStack from apps.utils.middlewares import TokenAuthMiddleware
import apps.monitor.routing import apps.ws.routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings')
application = ProtocolTypeRouter({ application = ProtocolTypeRouter({
"http": get_asgi_application(), "http": get_asgi_application(),
"websocket": AuthMiddlewareStack( "websocket": TokenAuthMiddleware(
URLRouter( URLRouter(
apps.monitor.routing.websocket_urlpatterns apps.ws.routing.websocket_urlpatterns
) )
) )
}) })