我的WebSocket工作正常,但不向组发送任何数据
# settings.py
INSTALLED_APPS = [
'daphne',
# admin interface
'jet',
# django apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 3rd party
'django_otp',
'django_otp.plugins.otp_totp',
'drf_spectacular',
'rest_framework',
'multiselectfield',
'django_celery_results',
'django_celery_beat',
'channels',
# my apps
"ads",
"authentication",
]
# WSGI_APPLICATION = 'gozle_ads.wsgi.application'
ASGI_APPLICATION = 'gozle_ads.asgi.application'
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("localhost", 6379)],
},
},
}
# consumers.py
import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
class BannerConsumer(WebsocketConsumer):
def connect(self):
self.accept()
self.room_name = "banner_changer"
self.room_group_name = "banner_changer_group"
async_to_sync(self.channel_layer.group_add)(
self.room_name, self.room_group_name
)
self.send(json.dumps({"messgae": "Connected to the banner websocket"}))
def receive(self, text_data=None):
async_to_sync(self.channel_layer.group_send)(
"banner_changer_group",
{
"type": "banner_ads_socket",
"value": f"{text_data}"
}
)
def disconnect(self, code):
print("DISCONNECTED")
def banner_ads_socket(self, event):
print("BANNER ADS")
print(event)
# asgi.py
import os
from django.core.asgi import get_asgi_application
from django.urls import re_path
from channels.routing import ProtocolTypeRouter, URLRouter
from ads.consumers import BannerConsumer
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gozle_ads.settings')
ws_patterns = [
re_path(r"ws/banner/", BannerConsumer.as_asgi())
]
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": URLRouter(ws_patterns),
})
字符串
当我向receive
方法发送数据时,什么都没有发生,方法banner_ads_socket
不工作。它不会引发任何错误。首先,我将消费者添加到我的组,然后向组发送数据。我从视频中复制了它。在中,这段代码可以工作,但我的代码不行。我该怎么办?
1条答案
按热度按时间4ngedf3f1#
这可能是由于
self.room_name
和self.room_group_name
如何在connect
中分配,并在group_add
和group_send
中引用。您应该使用
room_group_name
来添加组和发送消息,即字符串