miguelgrinberg / flask-sock

Modern WebSocket support for Flask.
MIT License
274 stars 24 forks source link

How to send json object to client? #18

Closed lucascr91 closed 2 years ago

lucascr91 commented 2 years ago

I use the example in this repository to build my application and now I can send and receive strings between client and server. Now I want to do the same thing using json objects. I was able to send a json object from client to server using:

document.getElementById("form").onsubmit = (ev) => {
  ev.preventDefault();
  const nameField = document.querySelector(".name");
  const ageField = document.getElementById("age");
  const clientData = {
    name: nameField.value,
    age: ageField.value,
  };
  socket.send(JSON.stringify(clientData));
};

(Before using socket.send(JSON.stringify(clientData)) I tried socket.emit('myEvent', clientData), but it didn't work and generates the error "socket.emit is not a function".)

But how can I do the reverse? I mean, how to send an object from server to client?

In my specific case a function in server side returns a python dictionary. I would like to send this dictionary as a javascript object in client side:

@sock.route('/echo')
def echo(sock):
    while True:
        data_receive = json.loads(sock.receive())
        data = bnb_balance(data_receive['name'], data_receive['age'])
        sock.send(data)

Of course, I can stringfy the data variable and send it as a string to client. But is there a more elegant way to do it, right?

miguelgrinberg commented 2 years ago

You are using the plain WebSocket protocol, which only supports text or binary messages. There is nothing in this protocol to send high-level structures.

Interesting that you tried socket.emit which is not something that WebSocket supports. You probably saw this in Socket.IO code, which builds a richer data exchange solution on top of WebSocket and HTTP. Maybe you should switch to Socket.IO if you want this handled for you.