XMLRPC

[ ROT ]

13 Sep 2013

Задачка из курса Распределённых Объектных технологий.

Клиент принимает a,b,c коэффициенты квадратного уравнения ax²+bx+c=0 и вызывает функции сервера, для нахождения корней x1 и x2.

Сервер предоставляет XMLRPC метод решения.

Сервер

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import math
from xmlrpc.server import SimpleXMLRPCServer

__author__ = 'Messiah'
HOST = "localhost"
PORT = 8080

class Solver(object):
    def __init__(self):
        pass

    def solve(self, a=0, b=0, c=0):
        try:
            a, b, c = (float(a),
                       float(b),
                       float(c))
        except ValueError:
            return "Incorrect input", 0
        if a == 0:
            return "It's not a quadratic equation", 0
        # вычисляем дискриминант
        D = b ** 2 - 4 * a * c
        if D < 0:
            return "Not real roots", 0
        x1 = (-b + math.sqrt(D)) / 2 / a
        if D == 0:
            # если дискриминант равен 0 - корни равны.
            x2 = x1
        else:
            x2 = (-b - math.sqrt(D)) / 2 / a
        return x1, x2

if __name__ == "__main__":
    server = SimpleXMLRPCServer((HOST, PORT))
    print("Listening on", PORT)
    S = Solver()
    # регистрируем функцию решателя в XMLRPC сервере
    server.register_function(S.solve, "solve")
    server.serve_forever()

Клиент

#!/usr/bin/python3
# -*- coding: utf-8 -*-

__author__ = 'Messiah'
HOST = "localhost"
PORT = 8080

from xmlrpc.client import ServerProxy

# подключаемся к серверу
proxy = ServerProxy("http://{}:{}".format(HOST, PORT))
while True:
    print("===================\nQuadratic solver")
    try:
        a, b, c = (float(input("Enter A: ")),
                   float(input("Enter B: ")),
                   float(input("Enter C: ")))
        if a == b == c == 0:
            break
        print("Roots for {}x^2 + ({})x + ({})".format(a, b, c))
    except ValueError:
        print("Incorrect input")
        continue

    try:
        # вызываем метод сервера.
        x1, x2 = proxy.solve(a, b, c)
        x1, x2 = float(x1), float(x2)
    except ValueError:
        print(x1)
        continue
    except Exception as e:
        print("Something wrong with server: ", e)
    else:
        print("are x1 = {}, x2 = {}".format(x1, x2))

GitHub