Django频道Websocket断开连接

时间:2019-01-04 15:36:06

标签: python-3.x websocket django-channels

我希望我的Django应用“ popinion1”通过文本消息与本地计算机进行通信。

点冻结:

asgi-redis==1.4.3
asgiref==2.3.2
async-timeout==3.0.1
autobahn==18.12.1
channels==2.1.3
daphne==2.2.4
Django==2.1.3
redis==2.10.6
Twisted==18.9.0

当我执行“ manage.py runserver”时,似乎存在连接或至少没有错误

但是,只要在终端中刷新浏览器,我就会得到:

  
      
  • 错误-ws_protocol-[故障实例:回溯:类'ValueError'>>:找不到路径'输入/'的路由[多行]   以结尾:WebSocket DISCONNECT / input / [127.0.0.1:50506]
  •   

“ / input /”是我的应用。 Firefox检查器报告:

  

Firefox无法通过ws://127.0.0.1:8000与服务器建立连接

/ input /是我的应用。

我的routing.py是

from django.conf.urls import url
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator, OriginValidator
from input.consumers import ChatConsumer


print('ChatConsumer: ', ChatConsumer.name)

application = ProtocolTypeRouter({
    'websocket': AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(
                [
                    url(r'^input/(?P<username>[\w.@+-]+)/$', ChatConsumer),
                ]
            )
        )
    )
})

html模板中的javascript:

<script>

    console.log(window.location)
    var loc = window.location
    var wsStart = 'ws://'
    if (loc.protocol == 'https:'){
        wsStart = 'wss://'
    }
    var endpoint = wsStart + loc.host + loc.pathname
    var socket = new WebSocket(endpoint)


    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>

我的消费者。py

import asyncio
import json
from django.contrib.auth import get_user_model
from channels.consumer import AsyncConsumer
from channels.db import database_sync_to_async
from .models import Thread, ChatMessage

from asgiref.sync import async_to_sync

class ChatConsumer(AsyncConsumer):
    name = 'ChatConsumer'

    async def websocket_connect(self, event):
        print('connected! ', event)
        await self.send({
            "type": "websocket.accept"
        })

    async def websocket_receive(self, event):
        print('receive! ', event)


    async def websocket_disconnect(self, event):
        print('disconnected! ', event)

settings.py中的CHANNEL_LAYERS

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'asgi_redis.core.RedisChannelLayer',
        'CONFIG': {
            'hosts': [('localhost', 6379)],
        },
        #'ROUTING': 'popinion_project.routing.channel_routing',
    }
}

那么route.py中的地址是否错误?还奇怪的是routing.py中最后一次导入“ ChatConsumer”。它是“未解决的参考”,但print语句有效。

  

print('ChatConsumer:',ChatConsumer.name)

我正在关注本教程

  

https://www.youtube.com/watch?v=RVH05S1qab8

我很高兴知道如何使websocket连接。希望提供所有必要的信息。预先感谢

1 个答案:

答案 0 :(得分:1)

我使用的解决方案。这与使用url有关。

from django.urls import re_path
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator, OriginValidator

from chat.consumers import ChatConsumer
    application = ProtocolTypeRouter({
    # Empty for now (http->django views is added by default)
    'websocket': AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(
                [
                    re_path(r"^messages/(?P<username>[\w.@+-]+)", ChatConsumer),
                ]
            )
        )
    )
})