0

How can I convert my byte stream (socket.recv()) to string or maybe how should I decode?

I want to build a connection to a server but when I try to decode my recv() bytestream then I got an UnicodeDecodeError which I can solve with add ignore to decode but then I got with utf-8 a string which I can't read (maybe utf-8 is the false codec, but how should I know which I have to use?)

This is what I get from the recv()

b'HTTP/1.1 200 OK\r\nDate: Tue, 14 May 2019 17:28:11 GMT\r\nServer: Apache/2.2.22 (Debian)\r\nAccept-Encoding\r\nContent-Encoding: gzip\r\nContent-Length: 5934\r\nKeep-Alive: timeout=2, max=5\r\nConnection: Keep-Alive\r\nContent-Type: text/html;charset=utf-8\r\n\r\n\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\xed]\
..
.a little bit more bytes 
...
 #3\x81\x15ntT   (at the end)
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • 1
    It says: "Content-Encoding: _gzip_", so probably the bytes that you can't read are actually compressed with GZIP and aren't meant to be converted to readable data without decompressing them first. Also, not all bytes are meant to represent valid text. Your profile picture can Breakpoint represented as a similar looking line of bytes, but you won't be able t somehow convert it to readable text. – ForceBru May 14 '19 at 17:36
  • but the whole text will be converted into text which I cant read, with python2, where you don't have to decode the bytes it was possible to read them (it was a json object) – Max Neumann May 14 '19 at 17:46
  • Then you should be able to read it in Python 3 as well, even without decoding (as you can see, you can read plain English even without decoding). Please post a [mcve] (a.k.a. a short snippet of your data that you can't read in Py 3, but can in Py 2). – ForceBru May 14 '19 at 17:49
  • Possible duplicate of [Python - converting sock.recv to string](https://stackoverflow.com/questions/13979764/python-converting-sock-recv-to-string) – Column01 May 14 '19 at 19:52

0 Answers0