问题描述
我有一个来自docker化渠道的简单聊天应用示例,但是当我打开2个聊天时遇到问题。
如果我打开第一个窗口并发送一条消息,那么消费者会捕获我的消息并回复组中的所有频道(此刻仅我)
然后,如果我打开另一个窗口并发送一条消息,则我在同一窗口(同一套接字)中收到两条消息,而在第一次窗口聊天中没有收到其他消息
但是我可以从旧窗口发送消息,我只是要在新窗口中看到此消息。
But i send messages,i cant see it and user2 can see it
我的消费者
# chat/consumers.py
import json
from channels.generic.websocket import AsyncWebsocketConsumer
class ChatConsumer(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
)
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
)
# Receive message from WebSocket
async def receive(self,text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
username = text_data_json['username']
# Send message to room group
await self.channel_layer.group_send(
self.room_group_name,{
'type': 'chat_message','message': message,'username': username
}
)
# Receive message from room group
async def chat_message(self,event):
message = event['message']
username = event['username']
# Send message to WebSocket
await self.send(text_data=json.dumps({
'message': message,'username': username
}))
docker-compose.yml
version: '3.1'
services:
chat:
build:
context: .
dockerfile: Dockerfile
volumes:
- .:/var/chat-core:z
depends_on:
- redis
ports:
- 8000:8000
redis:
image: redis:6.0.6
restart: always
ports:
- 6379:6379
Dockerfile
FROM python:3
RUN apt update & apt upgrade
RUN python3 -m pip install --upgrade pip
RUN python3 -m pip install Django
RUN python3 -m pip install -U channels
RUN python3 -m pip install channels_redis
workdir /var/chet-core
EXPOSE 8000
CMD ["python","manage.py","runserver","0.0.0.0:8000"]
我的settings.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file,see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values,see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# Security WARNING: keep the secret key used in production secret!
SECRET_KEY = '!)age)0rdjubmxu(v(gr-_bv$j4*n2#d^(b4r0$%n@aka+(b$g'
# Security WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application deFinition
INSTALLED_APPS = [
'channels','chat','django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware',]
ROOT_URLconf = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates','Dirs': [],'APP_Dirs': True,'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug','django.template.context_processors.request','django.contrib.auth.context_processors.auth','django.contrib.messages.context_processors.messages',],},]
# Channels
Asgi_APPLICATION = 'mysite.routing.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer','CONfig': {
"hosts": [('localhost',6379)],}
Wsgi_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3','NAME': BASE_DIR / 'db.sqlite3','TEST': {
'NAME': os.path.join(BASE_DIR,'db_test.sqlite3')
}
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS,JavaScript,Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)