Python socket simple example

Sometimes ago, accidentally, I’ve started experiments with python.
Accordingly, to external requirements, I must send some data and receive a response. I don’t know the length of the response, but the first two bytes are the response length.

Here some pieces of the experimental code

# part of a class that utilizes socket connection

server = (host, port)

# ...
# somewhere in the class connect to the socket
# self.sock.connect(self.server)
# ...

def create_socket(self, timeout=15):
  self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

def socket_send_and_read(self, command):
  # send data
  # prepare variable to store the response
  data = b''
  # current length of already read data
  current_len = 0
      tmp = self.sock.recv(1)
      data += tmp
      while tmp:
        # read byte from the response 
        tmp = self.sock.recv(1)
        data += tmp
        # in that case, I have first 2 bytes (bigendian) as the length of the response
        if len(data) == 2:
          current_len = int.from_bytes(data, byteorder='big')
        if 0 < current_len == len(data) - 2:
          # here, in fact, all response already read, so no reason to wait until timeout
          print('END READ!!', current_len, len(data))
    except Exception as e:
      print('Error', str(e))
      return data

Leave a Reply

Your email address will not be published. Required fields are marked *