Search code examples
javascriptpythonwebsockettornado

Sending websocket message to client with parameter


is there a way to send websocket message with parameter ? I would like to send a message to the website, and from the website be able to redirect it to correct div.

The concept is to send message + id, and depending on the id redirect it where it belongs. The id can be number or letter.

So far this is my partial server code (simplified):

  def on_message(self, message):
    global c
    if message == "w": 
    c = "8";
    if message == "s":
    c = "2"
    if c == '8' :
    self.write_message("This should appear in first div ")
    elif c == '2' :
    self.write_message("This should appear in second div ")

And client code:

<div id="output">First div</div>
<div id="output2">Second div</div>

 socket.onmessage = function(msg)
{
    showServerResponse(msg.data);
}
function showServerResponse(txt)
{
    var p = document.createElement('p');
    p.innerHTML = txt;
    document.getElementById('output').appendChild(p); 
}   

This is binded to send any message to div "output".

Should I override write_message function ? How should it look like ?

Thanks for any advice.


Solution

  • So, I will repair it to JSON but now I'm sending letters from website:

    socket.send("w")
    socket.send("s")
    

    and on server side are waiting JSON objects:

    forward = { "messageid": 1,
             "message": "First message"
           }
    backward = { "messageid": 2,
             "message": "Second message"
           }
    

    And depending on case I send back to client JSON:

    def on_message(self, message):
      global c
      if message == "w": 
      c = "8";
      if message == "s":
      c = "2"
      if c == '8' :
      self.write_message(json_encode(forward))
      elif c == '2' :
      self.write_message(json_encode(backward))
    

    Back in browser is function waiting for json object:

    <div id="output">First div</div>
    <div id="output2">Second div</div>
    
    socket.onmessage = function(msg){
     var message = JSON.parse(msg.data);
     if(message.messageid== 1)
      {
       showServerResponse(message.message)
      }
     if(message.messageid== 2)
      {
       showServerResponse2(message.message)
      }
    }
    

    And the function to show to div:

    function showServerResponse(txt)
    {
     var p = document.createElement('p');
     p.innerHTML = txt;
     document.getElementById('output').appendChild(p); 
    }   
    

    Second function is showServerResponse2(txt) sending it to 'output2'.

    This way you can send messages from server to client to different divs, depending on sent parameter, which was the original question. The thing is it is recommended to send every message with correct parameter, or it may be lost.