【问题标题】:ConnectionRefusedError: [Errno 10061] Connect call failed ('127.0.0.1', 6379) WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:56602]ConnectionRefusedError: [Errno 10061] Connect call failed ('127.0.0.1', 6379) WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:56602]
【发布时间】:2020-10-06 14:02:19
【问题描述】:

在这里,我需要使用 django 频道中的网络套接字连接另一个频道。我无法连接到另一个频道,它显示这样的错误。

consumers.py

import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer

class ChatConsumer(WebsocketConsumer):
    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
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()

    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message
            }
        )

    # Receive message from room group
    def chat_message(self, event):
        message = event['message']

        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'message': message
        }))

routing.py*(在 django 项目中)*

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import chat.routing

application = ProtocolTypeRouter({
    
    'websocket': AuthMiddlewareStack(
        URLRouter(
            chat.routing.websocket_urlpatterns
        )
    ),
})

routing.py*(在聊天应用中)*

from django.urls import re_path

from .consumers import ChatConsumer

websocket_urlpatterns = [
    re_path(r'ws/chat/(?P<room_name>\w+)/$',ChatConsumer),
]

views.py

from django.shortcuts import render

def index(request):
    return render(request, 'chat/index.html')

def room(request, room_name):
    return render(request, 'chat/room.html', {
    'room_name': room_name
    })

urls.py*(在聊天应用中)*

 
from django.contrib import admin
from django.urls import path
from  .views import index,room

app_name = 'chat'
urlpatterns = [
   
     path('', index, name='index'),
     path('<str:room_name>/', room, name='room'),
]

urls.py*(在主项目文件夹中)*

 
from django.contrib import admin
from django.urls import path,include
from chat.views import index

urlpatterns = [
    path('admin/', admin.site.urls),
     path('chat/',include('chat.urls',namespace = 'chat')),
]

settings.py

 

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 = '_94me+sc-lcgo-eo1zrf%!t!q8$rk2b)%e-58u^h2d#v8gzk#j'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'channels',
    'chat'
]

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 = 'justchat.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',
            ],
        },
    },
]

WSGI_APPLICATION = 'justchat.wsgi.application'
ASGI_APPLICATION = 'justchat.routing.application'
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('127.0.0.1', 6379)],
        },
    },
}

# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': str(BASE_DIR / 'db.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/'

【问题讨论】:

    标签: django django-channels


    【解决方案1】:

    您忘记运行redis 服务器。

    在官方教程中,它是通过docker 图像完成的。首先,您需要安装docker。之后在 6379 端口运行 redis 图像:

    docker run -p 6379:6379 -d redis:5
    

    更新:

    如果您使用的是 Windows,可能会出现一些问题。 django-channels 包含redisin-memory 通道层。一般来说,在开发中你不必使用redis,只需重新定义通道层后端选项:

    settings.py

    CHANNEL_LAYERS = {
        "default": {
            "BACKEND": "channels.layers.InMemoryChannelLayer"
        }
    }
    

    【讨论】:

    • 我不确定,你可以在windows上做,这篇文章可能对你有帮助:koukia.ca/…
    • 但是我可以告诉你如何在没有 redis 和 docker 的情况下执行此操作
    • 是的,请帮帮我
    【解决方案2】:

    如果您不使用 Docker。 Redis 可以这样设置。使用 Debian Linux 发行版、apt 包管理器和 systemctl。

    sudo apt-get install redis
    

    检查是否有效

    sudo systemctl status redis
    

    控制台输出

    ● redis-server.service - Advanced key-value store
       Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled)
       Active: active (running) since Wed 2021-12-29 09:59:45 EST; 6min ago
         Docs: http://redis.io/documentation,
               man:redis-server(1)
     Main PID: 10411 (redis-server)
        Tasks: 4 (limit: 4915)
       Memory: 7.1M
       CGroup: /system.slice/redis-server.service
               └─10411 /usr/bin/redis-server 127.0.0.1:6379
    
    Dec 29 09:59:45 debian systemd[1]: Starting Advanced key-value store...
    Dec 29 09:59:45 debian systemd[1]: redis-server.service: Can't open PID file /run/redis/redis-se
    Dec 29 09:59:45 debian systemd[1]: Started Advanced key-value store.
    

    【讨论】:

    • 用户是否表明他们正在使用使用 apt 和 systemctl 的 linux 发行版?无论哪种方式,您都应该指定这只是安装和运行 redis 的众多方法之一,它可能根本不适用于这个问题。
    • 我的错误的搜索查询导致了这个问题。为遇到类似问题的人添加了答案。我同意你的看法。我将添加一个额外的描述。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 2020-05-15
    • 2014-12-22
    • 2023-03-18
    • 2017-05-16
    • 2023-01-17
    • 2020-08-27
    相关资源
    最近更新 更多