Search code examples
pythonooptcpbytestream

TCP Receive in Python, reading the data out


My Python script is as below (sensitive data removed where necessary)

import socket

class TCPConnection:
    def __init__(self, sock=None):
        if sock is None:
            self.sock = socket.socket(
                            socket.AF_INET, socket.SOCK_STREAM)
        else:
            self.sock = sock

    def connect(self, host, port):
        try:
            self.sock.connect((host, port))
            print('Successful Connection')
        except:
            print('Connection Failed')

    def readlines(self):
        data = self.sock.recv(1024)
        print(data)


if __name__ == '__main__' : 
    listen = TCPConnection()
    listen.connect('**.**.**.**',##)
    listen.readlines()

I'm getting the following output.

Successful Connection
b'\x01\x00\xc7\x00\x08\x01\x07\t\x00\x00\x00\x03='

What do I now need to do to make the printed output from the readlines() function more friendly? From the look of it, I know it's in bytes, but beyond that, I'm lost.

All help is gracefully received.


Solution

  • You can decode the message before printing it:

    def readlines(self):
        data = self.sock.recv(1024).decode()
        print(data)
    

    but still please consider that your data is not "ASCII" or "UTF-8".