Beispiel #1
0
class TextProtocolClient:
    def __init__(self):
        self.sock = TextSocket()

    def connect(self, host, port):
        try:
            self.sock.connect((host, port))
        except socket.error as e:
            raise ConnectionError(e.strerror)

    def write_command(self, cmd, *args):
        """
        write_command() -> None
        Send command to the server.
        """
        self.sock.write(cmd)
        if len(args):
            self.sock.write(' ')
        self.sock.write(' '.join(['"' + a + '"' for a in args]))
        self.sock.write('\n')

    def parse_dict(self, line):
        """
        parse_dict(line) -> dict
        parse_dict parses protocol key-value line to dict.
        """
        try:
            return parse_dict(line)
        except ValueError as e:
            raise ProtocolError('Failed to parse server response.' + str(e))

    def read_response(self):
        """
        read_response() -> [response lines]
        bool return value indicates is server responsed with OK or ERROR status.
        """
        status = self.sock.readline()
        lines = []

        while True:
            s = self.sock.readline()

            if s:
                lines.append(s)
            else:
                break

        if status == Client.STATUS_OK:
            return lines
        elif not len(status):
            raise ConnectionError('Server connection is dead')
        else:
            raise ProtocolError(' '.join(lines))
Beispiel #2
0
class TextProtocolClient:
    def __init__(self):
        self.sock = TextSocket()

    def connect(self, host, port):
        try:
            self.sock.connect((host, port))
        except socket.error as e:
            raise ConnectionError(e.strerror)

    def write_command(self, cmd, *args):
        """
        write_command() -> None
        Send command to the server.
        """
        self.sock.write(cmd)
        if len(args):
            self.sock.write(' ')
        self.sock.write(' '.join(['"' + a + '"' for a in args]))
        self.sock.write('\n')

    def parse_dict(self, line):
        """
        parse_dict(line) -> dict
        parse_dict parses protocol key-value line to dict.
        """
        try:
            return parse_dict(line)
        except ValueError as e:
            raise ProtocolError('Failed to parse server response.' + str(e))

    def read_response(self):
        """
        read_response() -> [response lines]
        bool return value indicates is server responsed with OK or ERROR status.
        """
        status = self.sock.readline()
        lines = []

        while True:
            s = self.sock.readline()

            if s:
                lines.append(s)
            else:
                break

        if status == Client.STATUS_OK:
            return lines
        elif not len(status):
            raise ConnectionError('Server connection is dead')
        else:
            raise ProtocolError(' '.join(lines))