Esempio n. 1
0
    def user_online(self, client: Client, response):
        username = response['data']
        self.history[username] = []

        self.users.add(username)
        client.send_dh_request(username, True)  # 发送握手请求
        self.list_users.setModel(QStringListModel(self.users))
Esempio n. 2
0
    def refresh_user_list(self, client: Client, response):
        self.users = set(response['data'])
        self.users.add(self.public_room_name)
        for username in self.users:
            self.history[username] = []
            client.send_dh_request(username, True)  # 发送握手请求

        self.list_users.setModel(QStringListModel(self.users))
Esempio n. 3
0
    def initialize(self):

        # iterate clients.
        self.__clients__ = {}
        for path in self.directory.paths(dirs_only=True):
            client = Client(
                server=self.id,
                username=gfp.name(path=path),
            )
            response = client.initialize()
            if not response.success: return response
            self.__clients__[client.username] = client

        # handler.
        return dev0s.response.success(
            f"Successfully initialized server [{self.id}].")
Esempio n. 4
0
def run_game(c: Client):
    c.connect()
    welcome = c.responses.get()
    if welcome != 'WELCOME':
        raise RuntimeError('invalid first message; got:\t', welcome)
    c.write(c.team)
    c.get_initial_data()
    ai = AI(c)
    while c.r_th.isAlive():
        msg = c.messages.get() if not c.messages.empty() else False
        if msg and msg == 'dead':
            return
        ai.make_decision(msg)
        c.send_information()
Esempio n. 5
0
    def setUp(self):
        """ Initialisation des tests.

        Instanciation d'un serveur, d'un client et initialisation de 
        la connexion.

        """

        self.serveur = Serveur()
        self.client = Client("localhost", 12800)

        # Démarrage du serveur
        self.serveur.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.serveur.socket.bind((self.serveur.hote, self.serveur.port))
        self.serveur.socket.listen(5)

        # Connexion du client
        self.client.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client.socket.connect((self.client.hote, self.client.port))

        # Acceptation de la connexion
        self.connexion_client, infos_connexion = self.serveur.socket.accept()
Esempio n. 6
0
def solution(C, P, filepath):
    ### Your code goes here ##
    # use rad_print instead of print with filepath as first argument
    # ex:	rad_print(filepath, C, P)

    clients = []
    for L, D in P:
        client = Client(L, D)
        clients.append(client)
    ingredients = set()
    for client in clients:
        ingredients.update(client.L)
        ingredients = ingredients - client.D
    rad_print(filepath, len(ingredients), *ingredients)
Esempio n. 7
0
class ServeurTest(unittest.TestCase):
    """ Test cases utilisés pour tester les fonctions du module serveur """
    def setUp(self):
        """ Initialisation des tests.

        Instanciation d'un serveur, d'un client et initialisation de 
        la connexion.

        """

        self.serveur = Serveur()
        self.client = Client("localhost", 12800)

        # Démarrage du serveur
        self.serveur.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.serveur.socket.bind((self.serveur.hote, self.serveur.port))
        self.serveur.socket.listen(5)

        # Connexion du client
        self.client.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client.socket.connect((self.client.hote, self.client.port))

        # Acceptation de la connexion
        self.connexion_client, infos_connexion = self.serveur.socket.accept()

    def tearDown(self):
        """ Fermeture de la connexion et des sockets client et serveur """

        # Fermeture des connexions
        self.serveur.socket.close()
        self.client.socket.close()
        self.connexion_client.close()

    def test_envoyer_message(self):
        """ Teste la connexion par l'envoie et la reception d'un message """

        # Envoie d'un message test
        self.serveur.envoyer_msg(self.connexion_client, "test")

        # Vérification du message test reçu
        msg = self.client.recevoir()
        self.assertEqual(msg, "test")
Esempio n. 8
0
        print(line)
        continueAction()


def continueProgram(option):
    if (option == '0'):
        print('Closing application...')
        print('Aplication closed.')
        sys.exit()
    else:
        caseList = (caseOption_1(option), caseOption_2(option),
                    caseOption_3(option), caseOption_4(option),
                    caseOption_5(option), caseOption_6(option),
                    caseOption_7(option), caseOption_8(option),
                    caseOption_9(option))
        for option in range(1, 10):
            return caseList[option]


# Start the program
clientData = getClientData()

# create a new instace of the Client and Credit class
client = Client(clientData['name'], clientData['age'], clientData['income'],
                clientData['needToBorrow'])
credit = Credit(clientData['income'], clientData['needToBorrow'],
                caseOption_5('installments'))
ctype = loanType()

printActionOptions()
Esempio n. 9
0
import sys
from classes.client import Client

if __name__ == "__main__":
    """Main-Funktion des Clients"""

    client = Client()  # Erstelle neue Instanz der Klasse Client
    sys.exit(client.run())  # Führe den Client aus
Esempio n. 10
0
def handle_client(connection, address):
    client = Client(connection, address)
    try:
        while True:
            client.send_message(enums.MessageType.INFO,
                                "Can you please indicate your username?")
            client_username = client.receive_message()
            if client_username == "/exit":
                commands.general_exit(client, None, None)
                client.get_connection().shutdown(socket.SHUT_RDWR)
                client.get_connection().close()
                print("[%s] Client from IP address %s disconnected!" %
                      (datetime.now().strftime(
                          settings.DATETIME_FORMAT), client.get_address()))
                return True

            if len(client_username) < 3:
                client.send_message(
                    enums.MessageType.ERROR,
                    "Your username must be at least 3 characters long!")
                continue

            # Check if client username is banned
            client_banned = persistence.users.is_banned(client_username)
            if isinstance(client_banned, bool) and client_banned:
                client.send_message(
                    enums.MessageType.ERROR,
                    "Your username is permanently banned from the server!")
                client.get_connection().shutdown(socket.SHUT_RDWR)
                client.get_connection().close()
                print("[%s] Client with username %s is permanently banned!" %
                      (datetime.now().strftime(
                          settings.DATETIME_FORMAT), client_username))
                return True
            elif client_banned > 0:
                client.send_message(
                    enums.MessageType.ERROR,
                    "Your username is banned from the server for %d more hours!"
                    % client_banned)
                client.get_connection().shutdown(socket.SHUT_RDWR)
                client.get_connection().close()
                print(
                    "[%s] Client with username %s is banned for %d more hours!"
                    % (datetime.now().strftime(settings.DATETIME_FORMAT),
                       client_username, client_banned))
                return True

            if client_username in globals.client_list:
                client.send_message(
                    enums.MessageType.ERROR,
                    "The indicated username is already connected!")
            elif persistence.users.client_exists(client_username):
                client.send_message(
                    enums.MessageType.INFO,
                    "This username is registered, please indicate your password!"
                )
                client_password = client.receive_message()
                if persistence.users.get_client(client_username,
                                                client_password):
                    client.set_logged(True)
                    client.set_level(
                        persistence.users.get_level(client_username))
                    client.send_message(enums.MessageType.INFO,
                                        "You are now logged in!")
                    break
                else:
                    client.send_message(
                        enums.MessageType.ERROR,
                        "The typed password is wrong, please try again!")
            else:
                break

        client.set_username(client_username)
        globals.client_list[client.get_username()] = client
        client.send_message(
            enums.MessageType.INFO,
            "You are now connected, %s!" % client.get_username())
        for channel_client in globals.channel_list["general"].get_clients():
            if channel_client in globals.client_list:
                globals.client_list[channel_client].send_message(
                    enums.MessageType.INFO,
                    "Client @%s connected from the server!" %
                    client.get_username())
        print("[%s] Client connected with username %s" %
              (datetime.now().strftime(
                  settings.DATETIME_FORMAT), client.get_username()))

        # Join 'general' channel by default
        commands.channel_join(client, "general", None)

        if not client.is_logged():
            client.send_message(
                enums.MessageType.INFO,
                "In order to use this chat you do need to register your username."
                "\nFor that just type '/register <password>'.")

        while True:
            try:
                message = client.receive_message()
                rmx = datetime.now()

                if not message:
                    print(
                        "[%s] Communication with the client on  IP address %s has been terminated..."
                        % (datetime.now().strftime(
                            settings.DATETIME_FORMAT), client.get_address()))
                    break
            except OSError:
                break

            print("[%s] Received from @%s on #%s: %s" %
                  (datetime.now().strftime(settings.DATETIME_FORMAT),
                   client.get_username(), client.get_channel(), message))
            if not commands.parse(client, message, rmx):
                break

        # Close client connection
        for channel in globals.channel_list.values():
            channel.remove_client(client.get_username())
        for channel_client in globals.channel_list["general"].get_clients():
            if channel_client in globals.client_list:
                globals.client_list[channel_client].send_message(
                    enums.MessageType.INFO,
                    "Client @%s disconnected from the server!" %
                    client.get_username())
        if client.get_username() in globals.client_list:
            globals.client_list.pop(client.get_username())
        client.get_connection().shutdown(socket.SHUT_RDWR)
        client.get_connection().close()
        print("[%s] Client %s disconnected!" % (datetime.now().strftime(
            settings.DATETIME_FORMAT), client.get_username()))
    except socket.error as error:
        client.get_connection().shutdown(socket.SHUT_RDWR)
        client.get_connection().close()
        if client.get_username() is not None:
            for channel in globals.channel_list.values():
                channel.remove_client(client.get_username())
            for channel_client in globals.channel_list["general"].get_clients(
            ):
                if channel_client in globals.client_list:
                    globals.client_list[channel_client].send_message(
                        enums.MessageType.INFO,
                        "Client @%s disconnected from the server!" %
                        client.get_username())
            if client.get_username() in globals.client_list:
                globals.client_list.pop(client.get_username())
        print("[%s] Client from IP address %s connection error! error: %s" %
              (datetime.now().strftime(
                  settings.DATETIME_FORMAT), address, error))
Esempio n. 11
0
# [IMPORTS]--------------------------------------------------------------------
import time
import os
import re

from threading import *
from classes.client import Client

# [MODULE INFO]----------------------------------------------------------------
__author__ = 'Guillaume Bally'
__date__ = '2018/12/19'
__version__ = '0.1.1'
__maintainer__ = 'Guillaume Bally'

# [GLOBALS] -------------------------------------------------------------------
CLIENT = Client("localhost", 12800)
MESSAGE = str()


# [FUNCTION] ------------------------------------------------------------------
def communication_server():
    """
	Server message thread
	"""

    while not CLIENT.game_finished:
        MESSAGE = CLIENT.listen()

        if MESSAGE == "START":
            print("=== Game start ! ===")
            CLIENT.game_started = True
Esempio n. 12
0
        args = parser.parse_args()
        assert args.p > 0 and len(args.n) > 0
    except (argparse.ArgumentError, AssertionError, TypeError):
        sys.exit(1)
    return args


def run_game(c: Client):
    c.connect()
    welcome = c.responses.get()
    if welcome != 'WELCOME':
        raise RuntimeError('invalid first message; got:\t', welcome)
    c.write(c.team)
    c.get_initial_data()
    ai = AI(c)
    while c.r_th.isAlive():
        msg = c.messages.get() if not c.messages.empty() else False
        if msg and msg == 'dead':
            return
        ai.make_decision(msg)
        c.send_information()


if __name__ == '__main__':
    params = get_params()

    client = Client(port=params.p,
                    name=params.n,
                    host=params.h if params.h is not None else '127.0.0.1')
    run_game(client)
Esempio n. 13
0
    def start(self):

        # check args.
        self.arguments.check(json=dev0s.defaults.options.json,
                             exceptions=[
                                 "--log-level", "--version", "--create-alias",
                                 "--non-interactive", "--developer", "--sudo",
                                 "--global", "--debug"
                             ])

        # migrations.
        self.__check_migrations__()

        # generate encryption.
        if not ssht00ls_agent.generated:
            response = manager.install_encryption(interactive=True)
            if response["error"] != None: self.stop(response=response)

        # activate encryption.
        else:
            response = manager.activate_encryption(interactive=True)
            if response["error"] != None: self.stop(response=response)

        ########################################################################
        #
        # Basics.
        #

        # help.
        if self.arguments.present(['-h', '--help']):
            self.docs(success=True, json=dev0s.defaults.options.json)

        # version.
        elif self.arguments.present(['--version']):
            self.stop(message=f"{ALIAS} version: " +
                      Files.load(f"{SOURCE}/.version").replace("\n", ""),
                      json=dev0s.defaults.options.json)

        # config.
        elif self.arguments.present('--config'):
            if dev0s.defaults.options.json:
                os.system(f"cat {ROOT_DIR.fp.path}/config/settings")
            else:
                os.system(f"nano {ROOT_DIR.fp.path}/config/settings")

        ########################################################################
        #
        # Web Server.
        #

        # developer start.
        elif self.arguments.present('--start') and self.arguments.present(
                '--developer'):
            response = website.django.start(
                host=self.arguments.get("--host",
                                        required=False,
                                        default="127.0.0.1"),
                port=self.arguments.get("--port", required=False,
                                        default=8001),
            )
            self.stop(response=response)

        # start.
        elif self.arguments.present('--start'):
            response = manager.service.start()
            self.stop(response=response)

        # stop.
        elif self.arguments.present('--stop'):
            response = manager.service.stop()
            self.stop(response=response)

        # restart.
        elif self.arguments.present('--restart'):
            response = manager.service.restart()
            self.stop(response=response)

        # status.
        elif self.arguments.present('--status'):
            response = manager.service.status()
            if not response.success:
                self.stop(response=response)
            else:
                print(response.status)

        # reset logs.
        elif self.arguments.present('--reset-logs'):
            response = manager.service.reset_logs()
            self.stop(response=response)

        # tail.
        elif self.arguments.present('--tail'):
            response = manager.service.tail(
                global_=self.arguments.present("--global"),
                debug=self.arguments.present("--debug"))
            if not response.success:
                self.stop(response=response)
            else:
                print(response.logs)

        ########################################################################
        #
        # Installation.
        #

        # install a new key.
        elif self.arguments.present('--install'):
            response = Client().install(
                encoded=self.arguments.get("--encoded"))
            self.stop(response=response)

        ########################################################################
        #
        # Clients.
        #

        # client.
        elif self.arguments.present('--client'):
            alias = self.arguments.get("--client", chapter="clients")
            if "@" not in alias:
                self.docs(
                    error=f"Invalid <username>:<server> format.",
                    chapter="clients",
                    notes={
                        "<username>@<server>":
                        "Pack the username & server together as the client argument in the following format [<username>:<server>]."
                    },
                    json=dev0s.defaults.options.json,
                )
            username, server = alias.split("@")
            if server not in manager.servers.list():
                self.stop(
                    error=f"Specified server [{server}]  does not exist.")
            if client not in manager.servers[server].list():
                self.stop(
                    f"Specified client [{username}@{server}] does not exist.")
            server = manager.servers[server]
            client = server[username]

            # activate encryption & client key..
            response = manager.activate_encryption()
            if not response.success: self.stop(response=response)
            response = client.client.activate()
            if not response.success: self.stop(response=response)

            # vnc.
            if self.arguments.present('--vnc'):
                response = client.vnc.create_connection()
                if response.success:
                    print(response['message'])
                    print(
                        f"Visit url: {color.orange}{response['url']}{color.end}"
                    )
                else:
                    self.stop(response=response)

            # invalid.
            else:
                self.invalid(chapter="clients")

        ########################################################################
        #
        # AutoMount.
        #

        # automount.
        elif self.arguments.present('--automount'):

            # mount targets.
            if self.arguments.present('--mount'):

                # activate clients.
                response = automount.mount()
                if response["error"] != None: print(response["error"])
                else: print(response["message"])

            # mount targets.
            elif self.arguments.present('--unmount'):

                # activate clients.
                response = automount.unmount()
                if response["error"] != None: print(response["error"])
                else: print(response["message"])

            # mount targets.
            elif self.arguments.present('--remount'):

                # activate clients.
                response = automount.remount()
                if response["error"] != None: print(response["error"])
                else: print(response["message"])

            # invalid.
            else:
                self.invalid(chapter="automount")

        ########################################################################
        #
        # Invalid.
        #

        # invalid.
        else:
            self.invalid()
        """
Esempio n. 14
0
 def create_client(self, name):
     client = Client(name)
     self.clients.append(client)
     self.all_clients.append(client)
     return client
Esempio n. 15
0
                client.mon_tour = False
            elif msg.upper() == 'Q':
                client.envoyer(msg)
                client.mon_tour = False
            else:
                print("Commande invalide.")
        else:
            # Ce n'est pas au joueur de jouer.
            pass


# ---------------------------- Programme principal -----------------------------

print("==== Bienvenue dans Roboc! ====")

client = Client("localhost", 12800)
msg = str()

# Tentative de connexion au serveur
while True:
    try:
        client.connecter()
        break
    except:
        print("Erreur: connexion impossible avec le serveur. "
              "Nouvel essai dans 3 secondes...")
        time.sleep(3)

# Message de bienvenue
print("---------------------------------------------------")
print("Coups autorisés :")