class PresenceClient(object):
    def __init__(self):
        # Username is the first part of the JID it will use
        self.username = '******'
        # Domain name of the server
        self.domain = 'YLGW036487'
        # Port number to connect to, 5222 is default
        self.port = 5222
        # server to connect to
        self.server = 'server@YLGW036487'

        # Making a new instance of the NetworkingClient, providing it with domain and port
        self.network = NetworkingClient(server=self.domain, port=self.port)
        # starts a connection, and only continues if it is on a tls encrypted line
        if self.network.connect() == 'tls':
            # checks if authenticated with sasl authentication
            if 'sasl' == self.network.authenticate(username=self.username, domain=self.domain, secret='1234', resource='Test Server'):
                pass
                # On the client side we just use the default subscription handler
                # which accepts all subscriptions and subscribes back to the subscriber
                # it will use the default subscription handler if we don't specify any<br /><br />

                # Here we set the disconnect handler on the client side, remember not to invoke it with ()
                self.network.set_disconnect_handler(self.disconect_handler)
        else:
            # if no tls connection could be made, print a message and exit the program
            print 'could not open tls connection'
            sys.exit(0)

    # As with the server it is for handling unexpected disconnects from people in your roster
    def disconect_handler(self):
        # For this demonstration it just prints out a message. <br />
        # But you could make a client try to reconnect or in other ways handle that it has no connection
        print 'Server disconnected'
    def __init__(self):
        # Username is the first part of the JID it will use
        self.username = "******"
        # Domain name of the server
        self.domain = "YLGW036487"
        # Port number to connect to, 5222 is default
        self.port = 5222

        # Making a new instance of the NetworkingClient, providing it with domain and port
        self.network = NetworkingClient(server=self.domain, port=self.port)
        # starts a connection, and only continues if it is on a tls encrypted line
        if self.network.connect() == "tls":
            # checks if authenticated with sasl authentication
            if "sasl" == self.network.authenticate(
                username=self.username, domain=self.domain, secret="1234", resource="Test Server"
            ):
                # changes subscription behaviour, notice the lack of ()
                # this is important since we do not want to invoke it yet
                self.network.set_subscription_validator(self.server_subscription_acceptance)
                # Changes the disconnect handler to the given function.
                # Again make sure not to invoke the function by not giving it the ()<br />
                # It only fires on unexpected disconnects,
                # #meaning a client calling the disconnect function won't call this.
                self.network.set_disconnect_handler(self.server_disconnect_handler)
        else:
            # if no tls connection could be made, print a message and exit the program
            print "could not open tls connection"
            sys.exit(0)
class PresenceServer(object):
    def __init__(self):
        # Username is the first part of the JID it will use
        self.username = "******"
        # Domain name of the server
        self.domain = "YLGW036487"
        # Port number to connect to, 5222 is default
        self.port = 5222

        # Making a new instance of the NetworkingClient, providing it with domain and port
        self.network = NetworkingClient(server=self.domain, port=self.port)
        # starts a connection, and only continues if it is on a tls encrypted line
        if self.network.connect() == "tls":
            # checks if authenticated with sasl authentication
            if "sasl" == self.network.authenticate(
                username=self.username, domain=self.domain, secret="1234", resource="Test Server"
            ):
                # changes subscription behaviour, notice the lack of ()
                # this is important since we do not want to invoke it yet
                self.network.set_subscription_validator(self.server_subscription_acceptance)
                # Changes the disconnect handler to the given function.
                # Again make sure not to invoke the function by not giving it the ()<br />
                # It only fires on unexpected disconnects,
                # #meaning a client calling the disconnect function won't call this.
                self.network.set_disconnect_handler(self.server_disconnect_handler)
        else:
            # if no tls connection could be made, print a message and exit the program
            print "could not open tls connection"
            sys.exit(0)

    # It must take 1 parameter which is the jid the request comes from
    def server_subscription_acceptance(self, jid):
        # server only subscribes back to people named test1 and test 2<br />
        # to accomplish this, first make a regex search to find them.
        # since it will be a Jabber ID instance, we have to stringfy it. <br />
        # This means that the server will only know the status from test1 and test2.<br />
        # Therefore it will only send subscriber information to those 2.
        match = re.search("test[1^2]", str(jid))
        # if a match is found we allow the subscription and subscribe back
        if match:
            return (True, True)
        else:
            # if a match is not found, we allow the subscription but do not subscribe back
            return (True, False)

    # Function to handle a client disconnect from the "server" side
    def server_disconnect_handler(self):
        # As a test I just make it print out a message.
        # This is where you would make code that makes sure everything will still work even if someone disconnects
        print "A client disconnected"
    def __init__(self):
        # connection variables
        self.username = '******'
        self.domain = 'YLGW036487'
        self.server = "server@YLGW036487"
        self.port = 5222

        self.client_type = "trustfund"
        self.state = "wait"
        self.money_per_round = 100.0
        self.total_money = 0.0
        self.trust_fund_multiplication = 3.0

        # connecting
        self.network = NetworkingClient(server=self.domain, port=self.port)
        con = self.network.connect()
        if con == 'tls':
            print 'connected with tls'
        auth = self.network.authenticate(username=self.username, domain=self.domain, secret='1234', resource='Test Server')
        if auth == 'sasl':
            print 'authenticated with sasl'
    def __init__(self):
        # Username is the first part of the JID it will use
        self.username = '******'
        # Domain name of the server
        self.domain = 'YLGW036487'
        # Port number to connect to, 5222 is default
        self.port = 5222

        # General Variables
        self.state = "signup"
        self.investor_list = []
        self.trust_fund_list = []
        self.response_dict = {}
        self.investor_trust_fund_pairing = {}

        # Making a new instance of the NetworkingClient, providing it with domain and port
        self.network = NetworkingClient(server=self.domain, port=self.port)
        # starts a connection but doesn't receive messages
        print 'connected with', self.network.connect()
        # logging in
        print 'authenticated with ', \
            self.network.authenticate(username=self.username, domain=self.domain, secret='1234', resource='Test Server')
class BlockingClient(object):
    def __init__(self):
        # connection variables
        self.username = '******'
        self.domain = 'YLGW036487'
        self.server = "server@YLGW036487"
        self.port = 5222

        self.client_type = "trustfund"
        self.state = "wait"
        self.money_per_round = 100.0
        self.total_money = 0.0
        self.trust_fund_multiplication = 3.0

        # connecting
        self.network = NetworkingClient(server=self.domain, port=self.port)
        con = self.network.connect()
        if con == 'tls':
            print 'connected with tls'
        auth = self.network.authenticate(username=self.username, domain=self.domain, secret='1234', resource='Test Server')
        if auth == 'sasl':
            print 'authenticated with sasl'

    def start_when_ready(self):
        # register with server
        self.network.send_message(to=self.server, sender=self.network.id(), message="--register:"+self.client_type)
        # wait for pairing info
        while self.state != 'exit':
            if self.network.check_for_messages():
                msg = self.network.pop_message()
                if msg.body.find('--paired:') is not -1:
                    print 'Paired with ' + msg.body.lstrip('--paired:')

                # if selected and investor, starting up investment process
                if self.client_type == 'investor' and msg.body.find('--invest:start') is not -1:
                    print 'You get ', self.money_per_round, 'to invest, or keep'
                    invest_percentage = 50
                    # getting input from user, breaking out of loop when input is valid
                    while True:
                        try:
                            invest_percentage = int(raw_input('Enter what percentage you wish to invest: '))
                            if invest_percentage not in range(0, 101):
                                print 'Must be a number between 0 and 100'
                            else:
                                break
                        except ValueError:
                            print 'That is not a number and you know it ;)'
                    # notify server of investment
                    print 'You have invested: ', self.money_per_round * float(invest_percentage/100.0)
                    print 'You have kept: ', self.money_per_round - self.money_per_round * float(invest_percentage/100.0)
                    self.total_money = self.total_money + self.money_per_round - self.money_per_round * float(invest_percentage/100.0)
                    self.network.send_message(to=self.server, sender=self.network.id(), message='--investor:invest'+str(self.money_per_round*float(invest_percentage/100.0)))

                # investor waiting for response from trust fund
                if self.client_type == 'investor' and msg.body.find('--trustfund_pay:') is not -1:
                    payment = float(msg.body.lstrip('--trustfund_pay:'))
                    print 'Trustfund payment of: ', payment
                    self.total_money += payment
                    print 'Your total amount of money is: ', self.total_money

                # if selected trust fund, receive investment and decide how much to pay back
                if self.client_type == 'trustfund' and msg.body.find('--investment:') is not -1:
                    investment_received = float(msg.body.lstrip('--investment:'))
                    investment_received *= self.trust_fund_multiplication
                    invest_percentage = 50
                    print "Received investment of: ", investment_received
                    print "The invester shared " + str(investment_received / (self.money_per_round * self.trust_fund_multiplication) * 100.0) + '% of his money'
                    while True:
                        try:
                            invest_percentage = int(raw_input('Enter what'
                                                              ' percentage you wish to split with the investor: '))
                            if invest_percentage not in range(0, 101):
                                print 'Must be a number between 0 and 100'
                            else:
                                break
                        except ValueError:
                            print "That is not a number and you know it ;)"
                    money_shared = investment_received * float(invest_percentage) / 100.0
                    self.total_money = self.total_money + investment_received - money_shared
                    print 'Your total amount of money is: ' + str(self.total_money)
                    print 'You shared: ', money_shared
                    self.network.send_message(to=self.server, sender=self.network.id(), message='--trustfund_pay:'+str(money_shared))
            time.sleep(0.1)
Esempio n. 7
0
                                   service.server_jid,
                                   message=player_names,
                                   subject="start")
        service.generate_aggression_matrix()
        service.database.start_experimental_session("x", "x", "Dan Mønster", service.server_version)
        service.insert_session(service.experimental_round, game_phase=True)
        service.start_game_phase()
        service.register_jids()
    else:
        service.end_game_phase()


if __name__ == "__main__":
    service = ServerService()
    layout = LayoutHelper()
    network = NetworkingClient(service.domain)
    con = network.connect()
    if con is None:
        raise RuntimeError('Can\'t connect to the network')
    auth = network.authenticate(username=service.username, domain=service.domain, secret=service.secret)
    if auth is None:
        raise RuntimeError('Can\'t authenticate with given username and password')
    canvas.fps = 30
    canvas.fullscreen = False
    if service.started:
        layout.draw_start_stop_button('Stop', action=start_stop_button_action)
    else:
        layout.draw_start_stop_button('Start', action=start_stop_button_action)
    # deleting offline messages
    # need to have a small delay so that it will receive them before it start drawing
    sleep(0.2)
Esempio n. 8
0
                    print service.clicked_player.name
                else:
                    print service.clicked_player


def on_key_press(canvas, keyboard):
    """Method to handle keyboard presses during run time

    Currently does nothing on keypress
    """
    pass

if __name__ == '__main__':
    layout = LayoutHelper()
    service = ClientService()
    network = NetworkingClient(service.domain)
    con = network.connect()
    if con is None:
        raise RuntimeError('Can\'t connect to the network')
    auth = network.authenticate(username=service.username, domain=service.domain, secret=service.secret)
    if auth is None:
        raise RuntimeError('Can\'t authenticate with given username and password')
    network.send_message(to=service.server_jid, sender=service.jid, message=str(service.version), subject="register")

    canvas.on_key_press = on_key_press
    canvas.on_mouse_press = on_mouse_press
    canvas.fps = 30
    canvas.fullscreen = False
    # deleting offline messages
    # need to have a very little delay so that it will receive them before it start drawing
    sleep(0.2)
class BlockingServer(object):
    def __init__(self):
        # Username is the first part of the JID it will use
        self.username = '******'
        # Domain name of the server
        self.domain = 'YLGW036487'
        # Port number to connect to, 5222 is default
        self.port = 5222

        # General Variables
        self.state = "signup"
        self.investor_list = []
        self.trust_fund_list = []
        self.response_dict = {}
        self.investor_trust_fund_pairing = {}

        # Making a new instance of the NetworkingClient, providing it with domain and port
        self.network = NetworkingClient(server=self.domain, port=self.port)
        # starts a connection but doesn't receive messages
        print 'connected with', self.network.connect()
        # logging in
        print 'authenticated with ', \
            self.network.authenticate(username=self.username, domain=self.domain, secret='1234', resource='Test Server')

    # given a dictionary calculates if it has the same amount of entries as the shortest list of participant types
    def _have_all_responses(self, dict):
        if len(self.investor_list) <= len(self.trust_fund_list):
            if len(dict) == len(self.investor_list):
                return True
        else:
            if len(dict) == len(self.trust_fund_list):
                return True
        return False

    def game_round(self):
        # handling signup messages until start signal is given
        while self.state == "signup":
            # check for new signup messages
            if self.network.check_for_messages():
                msg = self.network.pop_message()
                # check if a investor registers
                if msg.body.find('--register:investor') is not -1:
                    print "adding investor"
                    self.investor_list.append(msg.sender)
                # checks if a trust fund registers
                elif msg.body.find('register:trustfund') is not -1:
                    print "adding trustfund"
                    self.trust_fund_list.append(msg.sender)
                # my start condition, in this case it's the number of players
                if len(self.investor_list) + len(self.trust_fund_list) == 4:
                    self.state = "pairing"
            time.sleep(0.1)

        # pairing investors and trust funds
        if self.state == 'pairing':
            # mixing investors and trustfunds for random pairing
            random.shuffle(self.investor_list)
            random.shuffle(self.trust_fund_list)
            for investor, trustfund in zip(self.investor_list, self.trust_fund_list):
                self.investor_trust_fund_pairing[investor] = trustfund

            # sending information to clients about their pairings
            for investor in self.investor_trust_fund_pairing:
                print str(investor) + "\tmatched with:\t" + str(self.investor_trust_fund_pairing[investor])
                self.network.send_message(to=investor, sender=self.network.id(), message='--paired:' + str(self.investor_trust_fund_pairing[investor]))
                self.network.send_message(to=self.investor_trust_fund_pairing[investor], sender=self.network.id(), message='--paired:' + str(investor))

            # sending the start signal for investors
            for investor in self.investor_trust_fund_pairing:
                self.network.send_message(to=investor, sender=self.network.id(), message='--invest:start')
            # changing server state to wait for responses
            self.state = "wait"

        # clearing the response dictionary before use
        self.response_dict = {}
        # waiting for responses from investors
        print 'getting investments'
        while self.state == 'wait':
            if self.network.check_for_messages():
                msg = self.network.pop_message()
                if msg.body.find('--investor:invest') is not -1:
                    investor = msg.sender
                    investment = msg.body.lstrip('--investor:invest')
                    self.response_dict[investor] = investment
                    print investor, 'invested: ', investment
                    # when all investors have responded change state
                    if self._have_all_responses(self.response_dict):
                        self.state = 'notify trustfunds'
            time.sleep(0.1)

        print 'getting responses from trust funds'
        # notifying trust funds of investments
        while self.state == 'notify trustfunds':
            # need to go through each investment and find the corresponding trust fund
            for investor in self.response_dict:
                trust_fund = self.investor_trust_fund_pairing[investor]
                self.network.send_message(to=trust_fund, sender=self.network.id(), message='--investment:'+self.response_dict[investor])
            self.state = 'trustfunds_shared'
            time.sleep(0.1)

        # clearing response dict for reuse
        self.response_dict = {}
        # notifying investors of received share from trust funds
        print 'sending responses to investors'
        while self.state == 'trustfunds_shared':
            if self.network.check_for_messages():
                msg = self.network.pop_message()
                if msg.body.find('--trustfund_pay:') is not -1:
                    # switching keys and values in the pairing dictionary, to find the trust fund -> invester link
                    trustfund_pairing_dict = dict((tru, inv) for inv, tru in self.investor_trust_fund_pairing.iteritems())
                    investor = trustfund_pairing_dict[msg.sender]
                    self.response_dict[investor] = msg.body.lstrip('--trustfund_pay:')
                    if self._have_all_responses(self.response_dict):
                        print 'received all responses, sending payment to investors'
                        for investor in self.response_dict:
                            self.network.send_message(to=investor, sender=self.network.id(), message='--trustfund_pay:'+self.response_dict[investor])
                        self.state = 'pairing'
            time.sleep(0.1)