def main(): listen_address, listen_port = parser_handling() database = ServerStorage() # Создание экземпляра класса - сервера и его запуск: server = Server(listen_address, listen_port, database) server.daemon = True server.start() # Печатаем справку: print_help() # Основной цикл сервера: while True: command = input('Введите комманду: ') if command == 'help': print_help() elif command == 'exit': break elif command == 'users': for user in sorted(database.users_list()): print(f'Пользователь {user[0]}, последний вход: {user[1]}') elif command == 'connected': for user in sorted(database.active_users_list()): print(f'Пользователь {user[0]}, подключен: {user[1]}:{user[2]}, время установки соединения: {user[3]}') elif command == 'loghist': name = input( 'Введите имя пользователя для просмотра истории. Для вывода всей истории, просто нажмите Enter: ') for user in sorted(database.login_history(name)): print(f'Пользователь: {user[0]} время входа: {user[1]}. Вход с: {user[2]}:{user[3]}') else: print('Команда не распознана.')
def __init__(self, bind_addr, port): self.logger = logging.getLogger(log_config.LOGGER_NAME) self.bind_addr = bind_addr self.port = port self.clients = [] self.users = {} self.storage = ServerStorage() self.__init_commands()
class MainWindow(QMainWindow): def __init__(self, parent=None): QWidget.__init__(self, parent) uic.loadUi(os.path.join(UI_DIR, 'config_server_window.ui'), self) self.storage = ServerStorage() self.__init_ui() def __init_ui(self): def switch_refresh(): if self.action_refresh.isChecked(): self.timer_refresh.start() else: self.timer_refresh.stop() def open_config_func(): win = ConfigWindow(self) win.exec_() self.open_config.triggered.connect(lambda: open_config_func()) self.action_refresh.triggered.connect(lambda: switch_refresh()) self.refresh() self.timer_refresh = QTimer() self.timer_refresh.setInterval(10000) self.timer_refresh.timeout.connect(self.refresh) def refresh(self): self.load_users() self.load_users_online() self.load_users_stats() self.load_history() def load_users(self): users = self.storage.get_users() # temp tbl = self.users_tbl fiil_table(tbl, users, ['id', 'name'], ['id', 'name']) def load_users_online(self): online = self.storage.get_users_online() tbl = self.users_online_tbl fiil_table(tbl, online, ['name'], ['name']) def load_users_stats(self): stats = self.storage.get_user_stats() tbl = self.user_stats_tbl fiil_table(tbl, stats, ['name', 'sent', 'recv'], ['User.name', 'UserStat.mes_sent', 'UserStat.mes_recv']) def load_history(self): history = self.storage.get_history() tbl = self.history_tbl fiil_table(tbl, history, ['id', 'name', 'date', 'ip'], [ 'LoginHistory.id', 'User.name', 'LoginHistory.datetime', 'LoginHistory.ip' ])
def main(): # server.py -a 192.168.1.2 -p 8079 database = ServerStorage() port, host, user = parce_command_line() server = Server(port, host, database) # server.daemon = True server.connect(timeout=0.5) server.response_to_clients()
def main(): config = load_config() port = config['port'] if config and 'port' in config else 7777 bind = config['bind'] if config and 'bind' in config else '' db_file = config[ 'database'] if config and 'database' in config else 'server_database.db3' ServerStorage(db_file) parser = argparse.ArgumentParser() parser.add_argument('-p', '--port', default=port, type=int, nargs='?', help='Port [default=7777]') parser.add_argument('-a', '--addr', default=bind, type=str, nargs='?', help='Bind address') args = parser.parse_args() addr = args.addr port = args.port server = Server(addr, port) server.start() application = QApplication(sys.argv) main_window = MainWindow() main_window.show() application.exec_()
def __init__(self, parent=None): QWidget.__init__(self, parent) uic.loadUi(os.path.join(UI_DIR, 'config_server_window.ui'), self) self.storage = ServerStorage() self.__init_ui()
def main(): # Загрузка файла конфигурации сервера config = configparser.ConfigParser() dir_path = os.path.dirname(os.path.realpath(__file__)) config.read(f"{dir_path}/{'server.ini'}") # Загрузка параметров командной строки, если нет параметров, то задаём # значения по умоланию. listen_address, listen_port = arg_parser( config['SETTINGS']['Default_port'], config['SETTINGS']['Listen_Address']) # Инициализация базы данных database = ServerStorage( os.path.join(config['SETTINGS']['Database_path'], config['SETTINGS']['Database_file'])) # Создание экземпляра класса - сервера и его запуск: server = Server(listen_address, listen_port, database) server.daemon = True server.start() # Создаём графическое окуружение для сервера: server_app = QApplication(sys.argv) main_window = MainWindow() # Инициализируем параметры в окна main_window.statusBar().showMessage('Server Working') main_window.active_clients_table.setModel(gui_create_model(database)) main_window.active_clients_table.resizeColumnsToContents() main_window.active_clients_table.resizeRowsToContents() # Функция обновляющяя список подключённых, проверяет флаг подключения, и # если надо обновляет список def list_update(): global new_connection if new_connection: main_window.active_clients_table.setModel( gui_create_model(database)) main_window.active_clients_table.resizeColumnsToContents() main_window.active_clients_table.resizeRowsToContents() with conflag_lock: new_connection = False # Функция создающяя окно со статистикой клиентов def show_statistics(): global stat_window stat_window = HistoryWindow() stat_window.history_table.setModel(create_stat_model(database)) stat_window.history_table.resizeColumnsToContents() stat_window.history_table.resizeRowsToContents() stat_window.show() # Функция создающяя окно с настройками сервера. def server_config(): global config_window # Создаём окно и заносим в него текущие параметры config_window = ConfigWindow() config_window.db_path.insert(config['SETTINGS']['Database_path']) config_window.db_file.insert(config['SETTINGS']['Database_file']) config_window.port.insert(config['SETTINGS']['Default_port']) config_window.ip.insert(config['SETTINGS']['Listen_Address']) config_window.save_btn.clicked.connect(save_server_config) # Функция сохранения настроек def save_server_config(): global config_window message = QMessageBox() config['SETTINGS']['Database_path'] = config_window.db_path.text() config['SETTINGS']['Database_file'] = config_window.db_file.text() try: port = int(config_window.port.text()) except ValueError: message.warning(config_window, 'Ошибка', 'Порт должен быть числом') else: config['SETTINGS']['Listen_Address'] = config_window.ip.text() if 1023 < port < 65536: config['SETTINGS']['Default_port'] = str(port) print(port) with open('server.ini', 'w') as conf: config.write(conf) message.information(config_window, 'OK', 'Настройки успешно сохранены!') else: message.warning(config_window, 'Ошибка', 'Порт должен быть от 1024 до 65536') # Таймер, обновляющий список клиентов 1 раз в секунду timer = QTimer() timer.timeout.connect(list_update) timer.start(1000) # Связываем кнопки с процедурами main_window.refresh_button.triggered.connect(list_update) main_window.show_history_button.triggered.connect(show_statistics) main_window.config_btn.triggered.connect(server_config) # Запускаем GUI server_app.exec_()
def server_launcher(): config = configparser.ConfigParser() dir_path = os.path.dirname(os.path.realpath(__file__)) config.read(f"{dir_path}/{'server.ini'}") listen_address, listen_port = argument_parser( config['SETTINGS']['Default_port'], config['SETTINGS']['Listen_Address']) database = ServerStorage( os.path.join(config['SETTINGS']['Database_path'], config['SETTINGS']['Database_file'])) server = Server(listen_address, listen_port, database) server.daemon = True server.start() server_app = QApplication(sys.argv) main_window = MainWindow() main_window.statusBar().showMessage('Server Working') main_window.active_clients_table.setModel(gui_create_model(database)) main_window.active_clients_table.resizeColumnsToContents() main_window.active_clients_table.resizeRowsToContents() def list_update(): global NEW_CONNECTION if NEW_CONNECTION: main_window.active_clients_table.setModel( gui_create_model(database)) main_window.active_clients_table.resizeColumnsToContents() main_window.active_clients_table.resizeRowsToContents() with CONFLAG_LOCK: NEW_CONNECTION = False def show_statistics(): global stat_window stat_window = HistoryWindow() stat_window.history_table.setModel(create_stat_model(database)) stat_window.history_table.resizeColumnsToContents() stat_window.history_table.resizeRowsToContents() stat_window.show() def server_config(): global config_window # Создаём окно и заносим в него текущие параметры config_window = ConfigWindow() config_window.db_path.insert(config['SETTINGS']['Database_path']) config_window.db_file.insert(config['SETTINGS']['Database_file']) config_window.port.insert(config['SETTINGS']['Default_port']) config_window.ip.insert(config['SETTINGS']['Listen_Address']) config_window.save_btn.clicked.connect(save_server_config) def save_server_config(): global config_window message = QMessageBox() config['SETTINGS']['Database_path'] = config_window.db_path.text() config['SETTINGS']['Database_file'] = config_window.db_file.text() try: port = int(config_window.port.text()) except ValueError: message.warning(config_window, 'Error', 'Port shall be a number') else: config['SETTINGS']['Listen_Address'] = config_window.ip.text() if 1023 < port < 65536: config['SETTINGS']['Default_port'] = str(port) print(port) with open('server.ini', 'w') as conf: config.write(conf) message.information(config_window, 'Ok', 'settings succesfully updated!') else: message.warning( config_window, 'Error', 'Port shall be in diaposon between 1024 and 65536') timer = QTimer() timer.timeout.connect(list_update) timer.start(1000) main_window.refresh_button.triggered.connect(list_update) main_window.show_history_button.triggered.connect(show_statistics) main_window.config_btn.triggered.connect(server_config) server_app.exec_()
class Server: __slots__ = ('bind_addr', '_port', 'logger', 'socket', 'clients', 'users', 'storage', 'commands', 'listener') TCP = (AF_INET, SOCK_STREAM) TIMEOUT = 5 port = Port('_port') def __init__(self, bind_addr, port): self.logger = logging.getLogger(log_config.LOGGER_NAME) self.bind_addr = bind_addr self.port = port self.clients = [] self.users = {} self.storage = ServerStorage() self.__init_commands() def __init_commands(self): self.commands = { 'get_users': self.storage.get_users_online, 'add_contact': self.storage.add_contact, 'rem_contact': self.storage.remove_contact, 'get_contacts': self.storage.get_contacts, } def start(self, request_count=5): self.socket = socket(*self.TCP) self.socket.settimeout(0.5) self.socket.bind((self.bind_addr, self.port)) self.logger.info( f'Config server port - {self.port}| Bind address - {self.bind_addr}' ) self.socket.listen(request_count) self.listener = ServerThread(self.__listen, self.logger) self.listener.start() self.__console() def __console(self): while True: msg = input('Enter command:\n') if msg.upper() == 'Q': break if msg[0] == '#': msg = msg[1:] command, *args = msg.split(' ') if command in self.commands: res = self.commands[command](*args) print(res) def __listen(self): self.logger.info('Start listen') while True: try: client, addr = self.socket.accept() except OSError: pass except Exception as ex: self.logger.error(ex) else: self.logger.info(f'Connection from {addr}') self.clients.append(client) i_clients, o_clients = [], [] try: i_clients, o_clients, ex = select(self.clients, self.clients, [], self.TIMEOUT) except OSError: pass except Exception as ex: self.logger.error(ex) requests = self.__get_requests(i_clients) if requests: self.__send_responses(requests, o_clients) @try_except_wrapper def __get_requests(self, i_clients): requests = {} for client in i_clients: try: request = get_data(client) requests[client] = request if request.action == RequestAction.PRESENCE: if request.body in self.users: requests.pop(client) send_data(client, Response(CONFLICT)) self.clients.remove(client) else: self.users[request.body] = client self.storage.login_user(request.body, client.getpeername()[0]) elif request.action == RequestAction.QUIT: self.__client_disconnect(client) except (ConnectionError, ValueError): self.__client_disconnect(client) except Exception as e: raise e return requests @try_except_wrapper def __send_responses(self, requests, o_clients): for client, i_req in requests.items(): other_clients = [c for c in o_clients if c != client] self.logger.info(client) self.logger.info(i_req) if i_req.action == RequestAction.PRESENCE: self.__send_to_client(client, Response(OK)) self.__send_to_all(other_clients, Response(BASIC, f'{i_req.body} connected')) elif i_req.action == RequestAction.QUIT: self.__client_disconnect(client) elif i_req.action == RequestAction.MESSAGE: msg = Msg.from_dict(i_req.body) if msg.to.upper() != 'ALL' and msg.to in self.users: self.__send_to_client(self.users[msg.to], Response(BASIC, str(msg))) else: self.__send_to_all(other_clients, Response(BASIC, str(msg))) elif i_req.action == RequestAction.COMMAND: command, *args = i_req.body.split() user = [u for u, c in self.users.items() if c == client].pop() args.insert(0, user) # o_resp = Response(ANSWER, self.__execute_command(command, *args)) o_resp = self.__execute_command(command, *args) self.__send_to_client(client, o_resp) else: self.__send_to_client(client, Response(INCORRECT_REQUEST)) self.logger.error(f'Incorrect request:\n {i_req}') @try_except_wrapper def __send_to_client(self, client, resp): try: send_data(client, resp) except ConnectionError: self.__client_disconnect(client) except Exception as e: raise e def __send_to_all(self, clients, resp): for cl in clients: self.__send_to_client(cl, resp) @try_except_wrapper def __client_disconnect(self, client): self.clients.remove(client) disconnected_user = [u for u, c in self.users.items() if c == client].pop() self.users.pop(disconnected_user) self.storage.logout_user(disconnected_user) disconnection_response = Response(BASIC, f'{disconnected_user} disconnected') for cl in self.clients: send_data(cl, disconnection_response) def __execute_command(self, command, *args): if command in self.commands: answer = self.commands[command](*args) if answer is False: return Response(SERVER_ERROR, 'Command error') elif isinstance(answer, list): answer = [str(a) for a in answer] return Response(ANSWER, answer) elif answer is None: return Response(ANSWER, 'Done') return Response(ANSWER, answer) else: return Response(INCORRECT_REQUEST, 'Command not found')
def main(): config = config_load() listen_address, listen_port = arg_parser( config['SETTINGS']['Default_port'], config['SETTINGS']['Listen_Address']) database = ServerStorage( os.path.join(config['SETTINGS']['Database_path'], config['SETTINGS']['Database_file'])) server = Server(listen_address, listen_port, database) server.daemon = True server.start() server_app = QApplication(sys.argv) main_window = MainWindow() main_window.statusBar().showMessage('Server Working') main_window.active_clients_table.setModel(gui_create_model(database)) main_window.active_clients_table.resizeColumnsToContents() main_window.active_clients_table.resizeRowsToContents() def list_update(): global new_connection if new_connection: main_window.active_clients_table.setModel( gui_create_model(database)) main_window.active_clients_table.resizeColumnsToContents() main_window.active_clients_table.resizeRowsToContents() with conflag_lock: new_connection = False def show_statistics(): global stat_window stat_window = HistoryWindow() stat_window.history_table.setModel(create_stat_model(database)) stat_window.history_table.resizeColumnsToContents() stat_window.history_table.resizeRowsToContents() stat_window.show() def server_config(): global config_window config_window = ConfigWindow() config_window.db_path.insert(config['SETTINGS']['Database_path']) config_window.db_file.insert(config['SETTINGS']['Database_file']) config_window.port.insert(config['SETTINGS']['Default_port']) config_window.ip.insert(config['SETTINGS']['Listen_Address']) config_window.save_btn.clicked.connect(save_server_config) def save_server_config(): global config_window message = QMessageBox() config['SETTINGS']['Database_path'] = config_window.db_path.text() config['SETTINGS']['Database_file'] = config_window.db_file.text() try: port = int(config_window.port.text()) except ValueError: message.warning(config_window, 'Error', 'Port will be a number') else: config['SETTINGS']['Listen_Address'] = config_window.ip.text() if 1023 < port < 65536: config['SETTINGS']['Default_port'] = str(port) dir_path = os.path.dirname(os.path.realpath(__file__)) with open(f"{dir_path}/{'server.ini'}", 'w') as conf: config.write(conf) message.information(config_window, 'Ok', 'Settings successfully saved!') else: message.warning(config_window, 'Error', 'Error shall be in range from 1024 to 65536') timer = QTimer() timer.timeout.connect(list_update) timer.start(1000) main_window.refresh_button.triggered.connect(list_update) main_window.show_history_button.triggered.connect(show_statistics) main_window.config_btn.triggered.connect(server_config) server_app.exec_()
def __init__(self, parent=None): QWidget.__init__(self, parent) uic.loadUi(os.path.join(UI_DIR, 'server.ui'), self) logging.getLogger(log_config.LOGGER_NAME).addHandler(UiLogHandler(self.logPtx)) self.storage = ServerStorage() self.__init_ui()