【问题标题】:Django Channels - Internal Custom Routing not workingDjango Channels - 内部自定义路由不起作用
【发布时间】:2016-09-24 03:07:23
【问题描述】:

我正在基于此示例 (https://github.com/andrewgodwin/channels-examples/blob/master/multichat/chat/routing.py) 构建一个聊天应用程序。 当 javascript 运行时(socket 已经打开,ws_connect 已经执行),它通过 websocket 发送 JSON。此 'message' 被路由到 ws_receive,然后将 JSON 加载到 'payload' 变量中。 'message' reply_channel 被添加到有效负载变量 (dict) 中。使用 Channels 命令,有效负载随后被发送并路由到 chat_join,在那里它应该简单地执行硬编码的 message.reply_channel.send。

所有步骤直到

payload['reply_channel'] = message.content['reply_channel']

工作正常。但随后有效负载没有被路由到 chat_join 消费者。如果路由正确,则没有正确读取 reply_channel 值,因此没有将消息发送回客户端。

似乎无法在这里找到断点。需要帮助修复此代码。

.js

//Join Room
socket.send(JSON.stringify({
    "command": "join",
    "room": "102"
}));

routing.py

from channels.routing import route
from MyProject.consumers import ws_connect, ws_receive, chat_join

websocket_routing = [
    route("websocket.connect", ws_connect),
    route("websocket.receive", ws_receive),    
]

custom_routing = [
    route("chat.receive", chat_join, command=r'^join$'),
]

consumers.py

from channels import Channel
def ws_receive(message):
    payload = json.loads(message['text'])
    payload['reply_channel'] = message.content['reply_channel']
    Channel("chat.receive").send(payload)

def chat_join(message):
    message.reply_channel.send({
        "text": json.dumps({
            "alpha": "1",
            "beta": "2",
        }),
    })

【问题讨论】:

  • 我遇到了同样的问题。单击房间名称按钮时没有任何反应。

标签: python django websocket channels django-channels


【解决方案1】:

Javascript 文件应该使用"text" 键发送数据。

来源:https://channels.readthedocs.io/en/latest/asgi.html#send-close

【讨论】:

    【解决方案2】:

    我尝试将我的 routing.py 更改为如下所示。我将自定义路由作为普通路由包含在 websocket_routing 中,它开始为我工作。希望这会有所帮助。

    websocket_routing = [
        # Called when WebSockets connect
        route("websocket.connect", ws_connect),
    
        # Called when WebSockets get sent a data frame
        route("websocket.receive", ws_receive), 
    
        # Called when WebSockets disconnect
        route("websocket.disconnect", ws_disconnect),    
    
    
        #Custom Routing
        #Join Chat
        route("chat.receive", chat_join, command=r'^join$'),
        route("chat.receive", chat_send, command=r'^send$'),
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      • 2013-11-04
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多