Django通道插座无法连接到消费者

问题描述 投票:0回答:1

我是一个新的套接字编程的新手;我被一个问题卡住了。我的客户端无法连接到消费者。

我的消费者

class TestConsumer(WebsocketConsumer):
    def websocket_connect(self):
        print("connected")
        self.accept()
        async_to_sync(self.channel_layer.group_add)('app', self.channel_name)
        print(self.scope['user'])

    def disconnect(self, close_code):
        async_to_sync(self.channel_layer.group_discard)('app', self.channel_name)

JavaScript代码

<script>
    // websocket scripts
    console.log(window.location)
    var loc = window.location
    var wsStart = 'ws://'
    if (loc.protocol == 'https:'){
        wsStart = 'wss://'
    }

    var endpoint =  wsStart + loc.host + loc.pathname + '/'
    console.log(endpoint)
    var socket = new WebSocket("ws://127.0.0.1:8000/test-view/")

    socket.onmessage = function(e){
        console.log("message", e)
    }
    socket.onopen = function(e){
        console.log("open", e)
    }
    socket.onerror = function(e){
        console.log("error", e)
    }
    socket.onclose = function(e){
        console.log("close", e)
    }


    </script>

路由

application = ProtocolTypeRouter({
    # (http->django views is added by default)
    'websocket': AuthMiddlewareStack(
        URLRouter(
            [
                url(r'^ws/test-view', consumers.TestConsumer),
            ]
        )
    ),
})

设置

ASGI_APPLICATION = 'apps.sockets.routing.application'

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

Redis正在运行

错误

WebSocket connection to 'ws://127.0.0.1:8000/test-view/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET

提示:根本没有打到消费者,当我第一次启动服务器的时候,它就打到了消费者。但当我加载页面时,它从来没有击中消费者,并崩溃在 var socket = new WebSocket("ws://127.0.0.1:8000/test-view/"). 这就是我目前所能推断的,所有的指南都告诉我做我已经在做的事情。我不知道为什么会发生这种情况,任何帮助都非常感激。

Django==2.2.11
Python==3.7
aioredis==1.2.0 
channels==2.2.0              
channels-redis==2.4.2
asgiref==3.2.7
daphne==2.5.0 
python django python-3.x websocket django-channels
1个回答
1
投票

你应该尝试 ws://127.0.0.1:8000/ws/test-view/ 而不是 ws://127.0.0.1:8000/test-view/

application = ProtocolTypeRouter({
    # (http->django views is added by default)
    'websocket': AuthMiddlewareStack(
        URLRouter(
            [
                url(r'^ws/test-view', consumers.TestConsumer),
            ]
        )
    ),
})

'webosocket' 定义了您正在使用 ws:// 惟有 url(r'^ws/test-view', consumers.TestConsumer) 定义您要添加的 /ws/test-view/ 后面的localhost连接到它。

© www.soinside.com 2019 - 2024. All rights reserved.