miguelgrinberg / flask-sock

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

How to ws.send(binary) #63

Closed tschesnok closed 1 year ago

tschesnok commented 1 year ago

Thanks for earlier help. As I understand it now, websockets can send binary or character data on a per packet basis. I'm able to send binary now to the server.. but I don't know how to return binary.

It seems the ws.send() function only send character strings from the server.. if I pass it a bytearray it will convert it to a text string that looks the same as if I passed it to print(bytearray).

what might I be doing wrong?

tschesnok commented 1 year ago

It seems when I use .hex() I can make it work as expected.. so I guess "Send" does auto-detect type.. but not all types? (I tell you python is hard for a C++ guy..)

tschesnok commented 1 year ago

I suspect that even when I send via Hex it is sending two characters per byte from server to client. I will know for sure when I switch the receiving client to C++. It seems when the buffer has a single number of 0x02 I get Buffer[0] = 0 Buffer[1] = 2 But this may be my python blues

tschesnok commented 1 year ago

I'm going to close this out since it works now with "ws.send (byte(data))

Here is what happened.. when

  1. Sending a bytearray -> it sends what you would get from sending it to print like "b"bytearray(b'\x02\x00\x00\x00\x00\x00\x" so a call to data[0] = "b" as in byte array

  2. sending data.hex = text string in hex format.. two character per number.

  3. ws.send (byte (data)) does the trick. All works as expected. This is required even though the data is already binary as part of a bytearray.

Thanks for listening..

miguelgrinberg commented 1 year ago

Python has a native type for binary data, called bytes. As a constant, you can create a byte sequence with b'this is bytes'. If you have a UTF-8 string you can convert it to a byte sequence with my_string.encode(). Hope this helps.