简体   繁体   中英

Waiting for websocket.receive consumer in django-channels

How to wait for a response from client after sending the client something using django-channels?

Whenever Group.send() is called from function send_to_client() and upon receiving the message by client, send_to_client() is expecting a response back from client which is getting received on websocket.receive channel.

Is there a way to return the response_msg in send_to_client() function?

Now I have reached here

Sample Code for consumers.py:

def ws_receive(message):
    response_msg = message.content['text']
    return response_msg

def send_to_client(param1, param2, param3):
    Group.send({
      "text" : json.dumps({
        "First" : param1,
        "Second" : param2,
       })
    })

So once the message reaches at the client side, the client will send a response back to the server which will be received by the ws_receive(message) function through the websocket.receive channel which is defined in the urls.py file,

channel_patterns = [
    route("websocket.receive", ws_receive),
    ...
] 

Is there a way to do this so that my function would look like this?

def send_to_client(...):
    Group.send(...)
    response_msg = #response message from client

Since you are recieving via a websocket, I am not sure if you would be able to even tell if the recieving thing is directly as a response for your request. I would rather put an id variable or something in the ongoing request, and maybe ask the client to put that id in the response as well. That might require both the sender and reciever to know the value of id as well (probably store in the db?)

Also, it do not seem logical to be blocked waiting for the response from websocket as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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