简体   繁体   English

WebSocket 连接失败 Django 通道

[英]WebSocket connection fails Django-channels

I am trying to create a socket-based application using Django-Channels, but I have a problem with connection to the WebSocket. To showcase my problem I created a test project.我正在尝试使用 Django-Channels 创建一个基于套接字的应用程序,但我在连接到 WebSocket 时遇到问题。为了展示我的问题,我创建了一个测试项目。

The error message from the JS Console:来自 JS 控制台的错误消息:

WebSocket connection to 'ws://127.0.0.1:8000/' failed: WebSocket 与“ws://127.0.0.1:8000/”的连接失败:

The error appears to happen on the line 25 of the html file, which is creating an instance of a WebSocket()该错误似乎发生在 html 文件的第 25 行,该文件正在创建 WebSocket() 的实例

Screenshot of the error错误截图

1个

Here is the code:这是代码:

# consumers.py

import ...


class ChatConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        self.groupname = 'dashboard'
        await self.channel_layer.group_add(
            self.groupname,
            self.channel_name,
        )
        await self.accept()

    ...
# routing.py

import...

websocket_urlpatterns = [
    path("", ChatConsumer.as_asgi()),
]
# views.py

import ...


def chatPage(request, *args, **kwargs):
    context = {}
    return render(request, "chatPage.html", context)
# asgi.py

import ...

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ChatApp.settings')

application = ProtocolTypeRouter(
    {
        "http": get_asgi_application(),
        "websocket": AuthMiddlewareStack(
            URLRouter(
                routing.websocket_urlpatterns
            )
        )
    }
)
# settings.py

...
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels.layers.InMemoryChannelLayer"
    }
}
...
<!--chatPage.html-->

...
    <script>
      const chatSocket = new WebSocket("ws://" + window.location.host + "/");

      document.querySelector("#id_message_send_input").focus();
      document.querySelector("#id_message_send_input").onkeyup = function (e) {
        if (e.keyCode === 13) {
          document.querySelector("#id_message_send_button").click();
        }
      };
      document.querySelector("#id_message_send_button").onclick = function (e) {
          const messageInput = document.querySelector(
              "#id_message_send_input"
          ).value;
          chatSocket.send(JSON.stringify({ message: messageInput, username : "{{request.user.username}}"}));
      };
      chatSocket.onmessage = function (e) {
        const data = JSON.parse(e.data);
        const div = document.createElement("div");
        div.innerHTML = data.username + " : " + data.message;
        document.querySelector("#id_message_send_input").value = "";
        document.querySelector("#id_chat_item_container").appendChild(div);
      };
    </script>
...

After some research I found out that the channel layers might not work correctly, but I'm not sure if this is the case and if so, would like to know the ways to fix it.经过一些研究,我发现通道层可能无法正常工作,但我不确定是否是这种情况,如果是,我想知道修复它的方法。

PS I'm currently working on windows, so I don't use redis, still I'm not sure that the same problem won't appear when I switch to redis. PS我目前在windows上工作,所以我没有使用redis,我仍然不确定当我切换到redis时是否会出现同样的问题。

For me downgrading the django channels package seemed to work.对我来说,降级 django 频道 package 似乎有效。

pip uninstall channels
pip install channels==3.0.5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM