Django WebSocket断开连接/ws/聊天/大厅/ [127.0.0.1:3022]

qv7cva1a  于 2023-01-14  发布在  Go
关注(0)|答案(5)|浏览(259)

我想创建聊天应用程序,我在这里遵循https://channels.readthedocs.io/en/latest/tutorial/part_2.html

chat/
    __init__.py
    routing.py
    urls.py
    settings.py
    wsgi.py

我把这个代码加到我的routing. py

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

application = ProtocolTypeRouter({
    # (http->django views is added by default)
    'websocket': AuthMiddlewareStack(
        URLRouter(
            chat.routing.websocket_urlpatterns
        )
    ),
})

在我的网站上settings.py

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

在我的网站上urls.py

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

在我聊天应用程序中

chat/
    __init__.py
    consumers.py
    routing.py
    templates/
        chat/
            index.html
            room.html
    urls.py
    views.py

我有www.example.comconsumers.py

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

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
        }))

这是我聊天中的代码〉www.example.comrouting.py

from django.urls import re_path

from . import consumers

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

在我的聊天中〉www.example.comviews.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
    })

我的聊天应用程序中有www.example.comurls.py in my chat app
从django.urls导入路径

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

我按照所有的方向,我复制粘贴代码,py的位置,tourorial中的一切,但我仍然得到这个错误

我错过什么了吗?
更新

当我尝试这个在我的pycharm终端码头运行-p 6379:6379-d redis:2. 8

0kjbasz6

0kjbasz61#

有几件事有问题。
1)您混合了asyncsync使用者代码。
我建议只使用async consumer,那么所有的方法都应该是async方法。
看起来您正在从同步上下文调用get_thread,但get_thread已 Package 在database_sync_to_async中,因此需要从异步上下文调用(并且需要等待)。
您还需要awaitself.channel_layer.group_add
2)在您的ThreadView中,您有一个ChatMessage.objects.create,您还应该通过线程通道组发送消息。

from channels.layers import get_channel_layer
channel_layer = get_channel_layer()

async_to_sync(channel_layer.group_send)(f"thread_{thread.id}", {"type": "chat.message", "text": ...})

您还需要将聊天消息保存到WebSocket_receive中的数据库。

sulc1iza

sulc1iza2#

我认为在您的settings.py文件中启用了一个名为CHANNEL_LAYER的模板变量(这就是错误的确切原因),因此请尝试从project/ www.example.com中删除这段代码settings.py

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': '',
        'CONFIG': {
           "hosts":[127.0.0.1],
        },
    },
}

在我的例子中,这是错误的根本原因。如果它不起作用,请尝试更改您的chat/routing.py文件。

5anewei6

5anewei63#

添加“.as_asgi()”

from django.urls import re_path

from . import consumers

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

ttp71kqs4#

我遇到了同样的问题,它的服务器断开的问题,这导致了所有这些。https://github.com/tporadowski/redis/releases/tag/v5.0.9下载最新版本并运行redis-server应用程序。

nimxete2

nimxete25#

如果你在linux下
1.首先通过运行以下命令安装docker-sudo snap install docker
1.然后运行以下命令-sudo chmod 666/var/run/docker. sock
1.然后运行这个命令docker run-p 6379:6379-d redis:5并启动Django服务器它可能会解决这个问题,它对我很有效,我想它对Windows和Mac也是一样的。

相关问题