【问题标题】:Django Channels - Handshaking & Connect, but websocket.connect function is not executedDjango Channels - 握手和连接,但未执行 websocket.connect 函数
【发布时间】:2017-07-26 13:09:27
【问题描述】:

我正在开发一个 django 项目,其频道涉及不同的应用程序。第一个应用(从传感器接收数据)有它自己的消费者和路由,以及第二个(更新登录用户列表)。

在第一个应用程序中一切正常。

在第二个应用程序中,握手完成并建立连接,但链接到websocket.receive 的函数没有执行。

from channels.routing import route, route_class
from channels.staticfiles import StaticFilesConsumer
from users.consumer import ws_connect, ws_disconnect

channel_routing = [
    route('websocket.connect', ws_connect, path=r'^/users/lobby/'),
    ...
]

还有ws_connect

import json
from channels import Group
from channels.handler import AsgiHandler
from channels.auth import channel_session_user,
    channel_session_user_from_http, channel_session

@channel_session_user_from_http
def ws_connect(message):
    print('test')

ws_connectprint('test') 永远不会被执行。此外,我在 javascript 中使用的 url 结尾甚至都没有关系。

var ws = new WebSocket('ws://127.0.0.1:8000/users/lobby/');

ws.onopen = function() {
  console.log('connect');
  ws.send('connect');
}

javascript 的ws 将与.../users/.../users/lobby/.../lobby/ 连接。

感谢您对此的任何提示!

【问题讨论】:

    标签: websocket connection django-channels


    【解决方案1】:

    由于我显然需要 50 名声望才能发表评论,所以即使我不确定这是适合你的解决方案,我也会做出回答。

    在复制制作频道的人制作的 github multichat 项目的部分内容时,我遇到了同样的问题。

    我的问题显然是我错过了拼写路由的轻微错误,因此它没有调用我为该路由设置的正确函数。

    所以我的建议是你到处检查路由,看看你是否搞砸了。我个人只在错误检查时检查了我的 APP 路由,但它在我的项目文件夹中,我弄乱了我的路由。

    可能导致此问题的另一件事是您的应用程序中只有一个路由,但主文件夹中没有。在这种情况下,您需要将其他应用程序路由包含在您想要的路径中,就像视图一样:

    from channels import include
    
    
    channel_routing = [
            include("crypto_chat.routing.websocket_routing", path=r"^/chat/stream/$"),
            include("crypto_chat.routing.chat_routing"),
    ]
    

    应用路由:

    from channels import route
    from .consumers import  ws_connect, ws_receive, ws_disconnect, user_offline, user_online, chat_send
    
    websocket_routing = [
        route("websocket.connect", ws_connect),
        route("websocket.receive", ws_receive),
        route("websocket.disconnect", ws_disconnect),
    ]
    
    chat_routing = [
        route("chat.receive", chat_send, command="^send$"),
        route("chat.receive", user_online, command="^online$"),
        route("chat.receive",user_offline, command="^offline$"),
    ]
    

    如果这没有帮助,那么我建议您前往 github 频道页面查看示例并比较两者。请记住,该项目可能是由较早版本的频道(也可能是 django)制作的。

    https://github.com/andrewgodwin/channels-examples

    希望它有所帮助,正如我所说,我会发表评论,但我显然不能因为我的代表......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-14
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 2021-03-07
      • 2016-12-21
      相关资源
      最近更新 更多