我正在构建基于此示例(https://github.com/andrewgodwin/channels-examples/blob/master/multichat/chat/routing.py)的聊天应用程序。 当javascript运行(套接字已经打开, ws_connect 已经执行)时,它会将JSON发送到websocket上。此'消息' 将路由到 ws_receive ,然后将JSON加载到'有效负载'变量。消息' 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",
}),
})
答案 0 :(得分:0)
Javascript文件应该使用"text"
密钥发送数据。
来源:https://channels.readthedocs.io/en/latest/asgi.html#send-close
答案 1 :(得分:0)
我尝试将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$'),
]