2

我正在基于此示例(https://github.com/andrewgodwin/channels-examples/blob/master/multichat/chat/routing.py)构建一个聊天应用程序。当 javascript 运行时(套接字已经打开,ws_connect已经执行),它通过 websocket 将 JSON 发送到。此“消息”被路由到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"
}));

路由.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$'),
]

消费者.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",
        }),
    })
4

2 回答 2

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$'),
]
于 2016-07-08T14:04:50.887 回答
0

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

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

于 2016-07-01T23:02:08.537 回答