Websocket与Django中的频道断开连接

时间:2019-01-01 19:51:34

标签: python django django-channels

我是Django的初学者。我想将Websockets与Channels一起使用。通过这种方式,我可以按照tutorial进行简单的聊天。

我向您展示我的文件。

聊天/consumers.py

from channels.generic.websocket import WebsocketConsumer
import json

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()

    def disconnect(self, close_code):
        pass

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

        self.send(text_data=json.dumps({
            'message': message
        }))

我的模板文件room.html:

<!-- chat/templates/chat/room.html -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Chat Room</title>
</head>
<body>
    <textarea id="chat-log" cols="100" rows="20"></textarea><br/>
    <input id="chat-message-input" type="text" size="100"/><br/>
    <input id="chat-message-submit" type="button" value="Send"/>
</body>
<script>
    var roomName = {{ room_name_json }};

    var chatSocket = new WebSocket(
        'ws://' + window.location.host +
        '/ws/chat/' + roomName + '/');

    chatSocket.onmessage = function(e) {
        var data = JSON.parse(e.data);
        var message = data['message'];
        document.querySelector('#chat-log').value += (message + '\n');
    };

    chatSocket.onclose = function(e) {
        console.error('Chat socket closed unexpectedly');
    };

    document.querySelector('#chat-message-input').focus();
    document.querySelector('#chat-message-input').onkeyup = function(e) {
        if (e.keyCode === 13) {  // enter, return
            document.querySelector('#chat-message-submit').click();
        }
    };

    document.querySelector('#chat-message-submit').onclick = function(e) {
        var messageInputDom = document.querySelector('#chat-message-input');
        var message = messageInputDom.value;
        chatSocket.send(JSON.stringify({
            'message': message
        }));

        messageInputDom.value = '';
    };
</script>
</html>

根路由配置:

# mysite/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
        )
        ),
    })

还有我的routing.py文件:

# chat/routing.py
from django.conf.urls import url

from . import consumers

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

当我运行ASGI服务器并到达 http://127.0.0.1:8000/chat/Test/ 页面时,出现以下消息错误:

HTTP GET /chat/Test/ 200 [0.00, 127.0.0.1:2807]
[Failure instance: Traceback: <class 'ValueError'>: No application configured for scope type 'websocket'
C:\Users\kevin\Envs\myproject\lib\site-packages\autobahn\websocket\protocol.py:2801:processHandshake
C:\Users\kevin\Envs\myproject\lib\site-packages\txaio\tx.py:429:as_future
C:\Users\kevin\Envs\myproject\lib\site-packages\twisted\internet\defer.py:151:maybeDeferred
C:\Users\kevin\Envs\myproject\lib\site-packages\daphne\ws_protocol.py:82:onConnect
--- <exception caught here> ---
C:\Users\kevin\Envs\myproject\lib\site-packages\twisted\internet\defer.py:151:maybeDeferred
C:\Users\kevin\Envs\myproject\lib\site-packages\daphne\server.py:198:create_application
C:\Users\kevin\Envs\myproject\lib\site-packages\channels\staticfiles.py:41:__call__
C:\Users\kevin\Envs\myproject\lib\site-packages\channels\routing.py:61:__call__
]
WebSocket DISCONNECT /ws/chat/Test/ [127.0.0.1:2814]

您对这个问题有想法吗? :)

question类似,但未提供答案。

谢谢!

编辑

我注意到了一件奇怪的事情,如果我在我的文件routing.py中输入了错误的代码,服务器将不会注意到它。好像它不读取该文件。例如,如果我像下面那样打开routing.py文件:

# chat/routing.py
from django.conf.urls import url

from . import consumers

websocket_urlpatterns = [
    url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer),ezvzev
]

服务器不显示任何错误消息。

3 个答案:

答案 0 :(得分:1)

我有同样的错误。我假设我们俩都遵循同一教程。

对我来说,这是chat / routing.py中路径末尾的多余美元符号:

# chat/routing.py
from django.conf.urls import url

from . import consumers

websocket_urlpatterns = [
    path('ws/chat/<str:room_name>/$', consumers.ChatConsumer),
]

删除“ $”后,一切正常。

答案 1 :(得分:0)

我发现了我的错误... 我将文件routing.py放在第一个目录中:sitetest \ 而我不得不将其放入sitetest \ sitetest \

答案 2 :(得分:0)

我有同样的问题。这是我的routing.py:

  from django.urls import re_path

  from .consumers import ChatConsumer

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

然后,我按照相同的问题代码编写了相同的教程。