Django WebSocket DISCONNECT / ws / chat / lobby / [127.0.0.1:3022]

用户名

我想创建聊天应用程序,在此处遵循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

我有consumers.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
        }))

这是我的chat> routing.py中的代码

from django.urls import re_path

from . import consumers

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

在我的chat> 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

从django.urls导入路径

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

我遵循所有方向,我复制粘贴代码,py的位置以及所有内容,但是仍然收到此错误

在此处输入图片说明

我错过了什么?

更新

在此处输入图片说明

当我在pycharm终端docker中尝试运行-p 6379:6379 -d redis:2.8

在此处输入图片说明

马特豪斯·伍拉德

这里有些问题。

1)你是混合asyncsync消费者的代码。

我建议只使用async consumer您所有的方法,然后应该是async方法。

看起来您是get_thread从同步上下文中调用的,但get_thread已被包裹在其中,database_sync_to_async因此需要从异步上下文中调用(并且需要等待)。

您还需要 await self.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": ...})

您还需要将chat消息保存在websocket_receive中的数据库中。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

在旧版Unix上,WEXITSTATUS的范围限制为0–127?

来自分类Dev

zookeeper无法打开localhost / 0:0:0:0:0:0:0:0:1:2181的套接字

来自分类Dev

Python-0 ** 0 == 1?

来自分类Dev

在R中将(0,1,0,0,1,1,1)转换为(0,0,0,1,0,1,2)

来自分类Dev

[“ $ {1:0:1}” ='-']的含义

来自分类Dev

Django model.BooleanField值为0/1

来自分类Dev

Django:[0,1]基数的一对多关系

来自分类Dev

获取所有数组的排列[1,1,1,1,1,0,0,0,0]

来自分类Dev

用于生成 [((0,0),0), ((0,1),0), ((1,0),0), ((1,1),0)] 的代码实际上给出了 [0 , 0, 0, 1, 1, 0, 1, 1],如何解决?

来自分类Dev

WebSocket WS SSL

来自分类Dev

(假-NOT(0))等于1?

来自分类Dev

1 << 0是什么?

来自分类Dev

Nhibernate转换1 = 0

来自分类Dev

有什么办法可以循环通过这些数字:-1 0、1 0、0 -1、0 1

来自分类Dev

验证0或1的参数

来自分类Dev

[$的含义?== 1] &&返回0

来自分类Dev

提取包含0 | 0,0 | 1,1 | 0和1 | 1的文件

来自分类Dev

Websocket chat implementation

来自分类Dev

从0-1-0缩小较大的数字

来自分类Dev

pow(1,0)返回0?

来自分类Dev

为什么0%0会产生1?

来自分类Dev

pow(1,0)返回0?

来自分类Dev

为什么 x^(-1/0) = 0

来自分类Dev

强制std :: string使用无符号字符(0到255)而不是字符(-128到127)

来自分类Dev

Matlab:从[0 0 1 0]降为[0 1 0 0]还是1011到1101的二进制降序?

来自分类Dev

WebSocket连接失败:一个或多个保留位处于打开状态:reserved1 = 0,reserved2 = 1,reserved3 = 1

来自分类Dev

WebSocket连接失败:一个或多个保留位处于打开状态:reserved1 = 0,reserved2 = 1,reserved3 = 1

来自分类Dev

为什么0 === -0为true,而1/0 === 1 / -0为false?

来自分类Dev

有什么更好的写方式[[-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1), (1,0),(1,1)]在Haskell吗?

Related 相关文章

  1. 1

    在旧版Unix上,WEXITSTATUS的范围限制为0–127?

  2. 2

    zookeeper无法打开localhost / 0:0:0:0:0:0:0:0:1:2181的套接字

  3. 3

    Python-0 ** 0 == 1?

  4. 4

    在R中将(0,1,0,0,1,1,1)转换为(0,0,0,1,0,1,2)

  5. 5

    [“ $ {1:0:1}” ='-']的含义

  6. 6

    Django model.BooleanField值为0/1

  7. 7

    Django:[0,1]基数的一对多关系

  8. 8

    获取所有数组的排列[1,1,1,1,1,0,0,0,0]

  9. 9

    用于生成 [((0,0),0), ((0,1),0), ((1,0),0), ((1,1),0)] 的代码实际上给出了 [0 , 0, 0, 1, 1, 0, 1, 1],如何解决?

  10. 10

    WebSocket WS SSL

  11. 11

    (假-NOT(0))等于1?

  12. 12

    1 << 0是什么?

  13. 13

    Nhibernate转换1 = 0

  14. 14

    有什么办法可以循环通过这些数字:-1 0、1 0、0 -1、0 1

  15. 15

    验证0或1的参数

  16. 16

    [$的含义?== 1] &&返回0

  17. 17

    提取包含0 | 0,0 | 1,1 | 0和1 | 1的文件

  18. 18

    Websocket chat implementation

  19. 19

    从0-1-0缩小较大的数字

  20. 20

    pow(1,0)返回0?

  21. 21

    为什么0%0会产生1?

  22. 22

    pow(1,0)返回0?

  23. 23

    为什么 x^(-1/0) = 0

  24. 24

    强制std :: string使用无符号字符(0到255)而不是字符(-128到127)

  25. 25

    Matlab:从[0 0 1 0]降为[0 1 0 0]还是1011到1101的二进制降序?

  26. 26

    WebSocket连接失败:一个或多个保留位处于打开状态:reserved1 = 0,reserved2 = 1,reserved3 = 1

  27. 27

    WebSocket连接失败:一个或多个保留位处于打开状态:reserved1 = 0,reserved2 = 1,reserved3 = 1

  28. 28

    为什么0 === -0为true,而1/0 === 1 / -0为false?

  29. 29

    有什么更好的写方式[[-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1), (1,0),(1,1)]在Haskell吗?

热门标签

归档