from server import Server from utils import MsgType if __name__ == '__main__': parser = argparse.ArgumentParser(description='RC Camera Car Server.') parser.add_argument('port', type=int, help='port to listen on') args = parser.parse_args() PORT = args.port HOST = '' DB_NAME = 'RCCar.db' logging.basicConfig( filename='server.log', level=logging.DEBUG, format='%(asctime)s, msg: %(message)s, level: %(levelname)s', datefmt='%m/%d/%Y %H:%M:%S' ) server = Server(HOST, PORT, DB_NAME) server.add_handler(MsgType.ACK, handlers.handle_ack) server.add_handler(MsgType.REG_USER, handlers.handle_register_user) server.add_handler(MsgType.REG_CAR, handlers.handle_register_car) server.add_handler(MsgType.LOGIN, handlers.handle_login) server.add_handler(MsgType.LINK, handlers.handle_link) server.add_handler(MsgType.CONN_CAR, handlers.handle_connect_car) server.add_handler(MsgType.MOVE, handlers.handle_movement) server.add_handler(MsgType.SET_LED, handlers.handle_set_led) server.add_handler(MsgType.GET_CARS, handlers.handle_get_cars)
# Example package with a console entry point from server import Server bot = Server("/tmp/dtskypebot.pid") bot.run()
def main(args): l = logger.logger(filename="server_log", user=config.get("Server", "name")) Server(config, l).start()
from Adafruit_MotorHAT_Motors import Adafruit_MotorHAT from TLV493D import TLV493D from motormanager import MotorManager from server import Server from callbacks import GUI from PyQt5 import QtWidgets import sys mh = Adafruit_MotorHAT() sensor = TLV493D() mm = MotorManager(mh, sensor) svr = Server(mm) mm.svr = svr if __name__ == "__main__": svr.start() app = QtWidgets.QApplication(sys.argv) window = GUI(sensor) window.show() sys.exit(app.exec_())
class TestGenerator(unittest.TestCase): engine = generator.make_engine( "stockfish", 6) # don't use more than 6 threads! it fails at finding mates server = Server(logger, "", "", 0) logger.setLevel(logging.DEBUG) def test_puzzle_1(self) -> None: # https://lichess.org/analysis/standard/3q1k2/p7/1p2Q2p/5P1K/1P4P1/P7/8/8_w_-_-_5_57#112 self.get_puzzle("3q1k2/p7/1p2Q2p/5P1K/1P4P1/P7/8/8 w - - 5 57", Cp(-1000), "h5g6", Mate(2), "d8g5 g6h7 g5g7") def test_puzzle_3(self) -> None: # https://lichess.org/wQptHOX6/white#61 self.get_puzzle( "1r4k1/5p1p/pr1p2p1/q2Bb3/2P5/P1R3PP/KB1R1Q2/8 b - - 1 31", Cp(-4), "e5c3", Mate(3), "f2f7 g8h8 f7f6 c3f6 b2f6") def test_puzzle_4(self) -> None: # https://lichess.org/eVww5aBo#122 self.get_puzzle("8/8/3Rpk2/2PpNp2/KP1P4/4r3/P1n5/8 w - - 3 62", Cp(0), "d6d7", Cp(580), "e3a3 a4b5 c2d4 b5b6 f6e5") # can't be done because there are 2 possible defensive moves def test_puzzle_5(self) -> None: # https://lichess.org/2YRgIXwk/black#32 self.get_puzzle( "r1b3k1/pp3p1p/2pp2p1/8/2P2q2/2N1r2P/PP2BPP1/R2Q1K1R w - - 0 17", Cp(-520), "d1d2", Cp(410), "e3h3 h1h3 f4d2") def test_puzzle_6(self) -> None: self.get_puzzle( "4nr1k/2r1qNpp/p3pn2/1b2N2Q/1p6/7P/BP1R1PP1/4R1K1 b - - 0 1", Cp(130), "f8f7", Cp(550), "e5g6 h8g8 g6e7") # https://lichess.org/YCjcYuK6#81 # def test_puzzle_7(self) -> None: # self.get_puzzle("7r/1k6/pPp1qp2/2Q3p1/P4p2/5P2/5KP1/1RR4r b - - 5 41", # Cp(-1500), "e6a2", Cp(530), "c1c2 a2e6 b1h1 h8h1 c2e2 e6d7 e2e7 d7e7 c5e7") # r1bq3r/pppp1kpp/2n5/2b1P1N1/3p2n1/2P5/P4PPP/RNBQ1RK1 b - - 1 10 # def test_puzzle_8(self) -> None: # self.get_puzzle("r1bq3r/pppp1kpp/2n5/2b1P1N1/3p2n1/2P5/P4PPP/RNBQ1RK1 b - - 1 10", # Cp(0), "f7g8", Mate(4), "d1b3 d7d5 e5d6 c8e6 b3e6 g8f8 e6f7") def test_puzzle_9(self) -> None: self.get_puzzle("7k/p3r1bP/1p1rp2q/8/2PBB3/4P3/P3KQ2/6R1 b - - 0 38", Cp(-110), "e6e5", Mate(2), "f2f8 g7f8 g1g8") # https://lichess.org/ejvEklSH/black#50 def test_puzzle_10(self) -> None: self.get_puzzle( "5rk1/pp3p2/1q1R3p/6p1/5pBb/2P4P/PPQ2PP1/3Rr1K1 w - - 6 26", Cp(-450), "g1h2", Mate(2), "h4g3 f2g3 b6g1") # https://lichess.org/3GvkmJcw#43 def test_puzzle_15(self): self.get_puzzle( "7k/pp1q2pp/1n1p2r1/4p3/P3P3/1Q3N1P/1P3PP1/5RK1 w - - 3 22", Cp(-80), "a4a5", Cp(856), "d7h3 g2g3 g6h6 f3h4 h6h4 g3h4 h3b3") def test_puzzle_16(self): self.get_puzzle("kr6/p5pp/Q4np1/3p4/6P1/2P1qP2/PK4P1/3R3R w - - 1 26", Cp(-30), "b2a1", Mate(1), "e3c3") def test_puzzle_17(self): self.get_puzzle("8/8/6k1/5R2/5KP1/5P2/5r2/8 w - - 17 66", Cp(-410), "g4g5", Cp(0), "f2f3 f4f3 g6f5") # one mover # def test_puzzle_17(self): # self.get_puzzle("6k1/Q4pp1/8/6p1/3pr3/4q2P/P1P3P1/3R3K w - - 0 31", # Cp(0), "d1d3", Cp(2000), "e3c1") def test_not_puzzle_1(self) -> None: # https://lichess.org/LywqL7uc#32 self.not_puzzle( "r2q1rk1/1pp2pp1/p4n1p/b1pP4/4PB2/P3RQ2/1P3PPP/RN4K1 w - - 1 17", Cp(-230), "b1c3", Cp(160)) def test_not_puzzle_2(self) -> None: # https://lichess.org/TIH1K2BQ#51 self.not_puzzle("5b1r/kpQ2ppp/4p3/4P3/1P4q1/8/P3N3/1nK2B2 b - - 0 26", Cp(-1520), "b1a3", Cp(0)) # def test_not_puzzle_3(self) -> None: # https://lichess.org/StRzB2gY#59 # self.not_puzzle("7k/p6p/4p1p1/8/1q1p3P/2r1P1P1/P4Q2/5RK1 b - - 1 30", # Cp(0), "d4e3", Cp(580)) def test_not_puzzle_4(self) -> None: self.not_puzzle( "r2qk2r/p1p1bppp/1p1ppn2/8/2PP1B2/3Q1N2/PP3PPP/3RR1K1 b kq - 6 12", Cp(-110), "h7h6", Cp(150)) # https://lichess.org/ynAkXFBr/black#92 def test_not_puzzle_5(self) -> None: self.not_puzzle("4Rb2/N4k1p/8/5pp1/1n2p2P/4P1K1/3P4/8 w - - 1 47", Cp(-40), "e8c8", Cp(610)) def test_not_puzzle_6(self) -> None: self.not_puzzle("5r1k/1Q3p2/5q1p/8/2P4p/1P4P1/P4P2/R4RK1 w - - 0 29", Cp(-1020), "g3h4", Cp(0)) # https://lichess.org/N99i0nfU#11 def test_not_puzzle_7(self): self.not_puzzle( "rnb1k1nr/ppp2p1p/3p1qp1/2b1p3/2B1P3/2NP1Q2/PPP2PPP/R1B1K1NR b KQkq - 1 6", Cp(-50), "c8g4", Cp(420)) def test_not_puzzle_8(self): self.not_puzzle( "r1bq1rk1/pp1nbppp/4p3/3pP3/8/1P1B4/PBP2PPP/RN1Q1RK1 w - - 1 11", Cp(-40), "d3h7", Cp(380)) def test_not_puzzle_9(self): self.not_puzzle( "5k2/5ppp/2r1p3/1p6/1b1R4/p1n1P1P1/B4PKP/1N6 w - - 2 34", Cp(0), "b1c3", Cp(520)) def test_not_puzzle_10(self): self.not_puzzle( "2Qr3k/p2P2p1/2p1n3/4n1p1/8/4q1P1/PP2P2P/R4R1K w - - 0 33", Cp(100), "c8d8", Cp(500)) def test_not_puzzle_11(self) -> None: self.not_puzzle( "2kr3r/ppp2pp1/1b6/1P2p3/4P3/P2B2P1/2P2PP1/R4RK1 w - - 0 18", Cp(20), "f1d1", Mate(4)) def test_not_puzzle_12(self): self.not_puzzle("5r1k/1Q3p2/5q1p/8/2P4p/1P4P1/P4P2/R4RK1 w - - 0 29", Cp(-1010), "g3h4", Cp(0)) # https://lichess.org/oKiQW6Wn/black#86 def test_not_puzzle_13(self): self.not_puzzle("8/5p1k/4p1p1/4Q3/3Pp1Kp/4P2P/5qP1/8 w - - 2 44", Cp(-6360), "e5e4", Mate(1)) def test_not_puzzle_14(self) -> None: # https://lichess.org/nq1x9tln/black#76 self.not_puzzle("3R4/1Q2nk2/4p2p/4n3/BP3ppP/P7/5PP1/2r3K1 w - - 2 39", Cp(-1000), "g1h2", Mate(4)) def test_not_puzzle_15(self) -> None: # https://lichess.org/nq1x9tln/black#76 self.not_puzzle("3r4/8/2p2n2/7k/P1P4p/1P6/2K5/6R1 w - - 0 43", Cp(-1000), "b3b4", Mate(4)) def test_not_puzzle_16(self) -> None: self.not_puzzle("8/Pkp3pp/8/4p3/1P2b3/4K3/1P3r1P/R7 b - - 1 30", Cp(0), "f2f3", Cp(5000)) def get_puzzle(self, fen: str, prev_score: Score, move: str, current_score: Score, moves: str) -> None: board = Board(fen) game = Game.from_board(board) node = game.add_main_variation(Move.from_uci(move)) current_eval = PovScore(current_score, not board.turn) result = generator.analyze_position(self.server, self.engine, node, prev_score, current_eval) self.assert_is_puzzle_with_moves( result, [Move.from_uci(x) for x in moves.split()]) def not_puzzle(self, fen: str, prev_score: Score, move: str, current_score: Score) -> None: board = Board(fen) game = Game.from_board(board) node = game.add_main_variation(Move.from_uci(move)) current_eval = PovScore(current_score, not board.turn) result = generator.analyze_position(self.server, self.engine, node, prev_score, current_eval) self.assertIsInstance(result, Score) def assert_is_puzzle_with_moves(self, puzzle: Union[Puzzle, Score], moves: List[Move]) -> None: self.assertIsInstance(puzzle, generator.Puzzle) if isinstance(puzzle, Puzzle): self.assertEqual(puzzle.moves, moves) @classmethod def tearDownClass(cls) -> None: cls.engine.close()
def main() -> int: server = Server() server.run() return 0
def __init__(self, *args): self.server = Server(*args) self.display_size_per = 0.8
def get_server(): return Server()
import sys from server import Server from threading import Thread from datetime import datetime from art import sword, colors, help_menu from time import sleep from random import choice server = Server(5002, '0.0.0.0') server.connection.bind((server.ip, server.port)) server.connection.listen() def connect(): print('\n\n') print(server.show_connections()) choice = int(input('What connection? ')) return server.connList[choice] def handler(conn): index = server.connList.index(conn) print(f'CONNECTED TO {server.ip[index]}') connected = True server.conn_session = conn while connected: try: to_send = input('CMD :') if to_send == 'server exit': sys.exit() elif to_send == 'background session':
def run(self): conn = Connection() states = get_states() actions = get_client_actions() server_actions = get_server_actions() transitions = get_transitions(states, actions, server_actions) machine = Machine(model=conn, states=states, transitions=transitions, initial='start', ignore_invalid_triggers=True, auto_transitions=True, use_pygraphviz=True) # machine.get_graph().draw('client_server_diagram.png', prog='dot') current_date = datetime.now() log_dir = 'output/log' pathlib.Path(log_dir + '/').mkdir( parents=True, exist_ok=True) # for Python > 3.5 YY_mm_dd_HH_MM_SS' log_filename = current_date.strftime(log_dir + '/' + 'log_' + '%Y_%m_%d_%H_%M_%S' + '.log') log_date_filename = 'output/log_date.log' output_Q_params_dir = 'output/output_Q_parameters' pathlib.Path(output_Q_params_dir + '/').mkdir( parents=True, exist_ok=True) # for Python > 3.5 output_Q_filename = current_date.strftime(output_Q_params_dir + '/' + 'output_Q_' + '%Y_%m_%d_%H_%M_%S' + '.csv') output_parameters_filename = current_date.strftime( output_Q_params_dir + '/' + 'output_parameters_' + '%Y_%m_%d_%H_%M_%S' + '.csv') output_dir = 'output/output_csv' pathlib.Path(output_dir + '/').mkdir(parents=True, exist_ok=True) # for Python > 3.5 output_filename = current_date.strftime(output_dir + '/' + 'output_' + self.algorithm + '_' + '%Y_%m_%d_%H_%M_%S' + '.csv') with open(log_date_filename, mode='a') as output_file: output_writer = csv.writer(output_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_NONE) output_writer.writerow( [current_date.strftime('%Y_%m_%d_%H_%M_%S'), self.algorithm]) # Write parameters in output_parameters_filename with open(output_parameters_filename, mode='w') as output_file: output_writer = csv.writer(output_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_NONE) output_writer.writerow(['algorithm_used', self.algorithm]) output_writer.writerow(['epsilon', self.epsilon]) output_writer.writerow(['max_steps', self.max_steps]) output_writer.writerow(['total_episodes', self.total_episodes]) output_writer.writerow(['alpha', self.alpha]) output_writer.writerow(['gamma', self.gamma]) if self.algorithm == 'sarsa_lambda' or self.algorithm == 'qlearning_lambda': output_writer.writerow(['lambda', self.lam]) # SARSA(lambda) algorithm # Initializing the Q-matrix if not self.disable_graphs: print("N states: ", len(states)) print("N actions: ", len(actions)) Q = np.zeros((len(states), len(actions))) E = np.zeros( (len(states), len(actions))) # trace for state action pairs start_time = time.time() x = range(0, self.total_episodes) y_timesteps = [] y_reward = [] y_cum_reward = [] x_global = [] y_global_reward = [] serv = Server() # Write into output_filename the header: Episodes, Reward, CumReward, Timesteps with open(output_filename, mode='w') as output_file: output_writer = csv.writer(output_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) output_writer.writerow( ['Episodes', 'Reward', 'CumReward', 'Timesteps']) cum_reward = 0 # Starting Q-learning training for episode in range(self.total_episodes): print("Episode", episode) t = 0 conn.state = states[1] state1 = states.index(conn.state) # retrieve current state # first server perform an action, then client chooses print("\tSTARTING FROM STATE", state1) done = False reward_per_episode = 0 act = serv.server_action(state1) print("\tSERVER ACTION", server_actions[act]) conn.trigger(server_actions[act]) state1 = states.index(conn.state) # retrieve current state action1 = self.choose_action(state1, actions, Q) while t < self.max_steps: state1 = states.index(conn.state) # retrieve current state print("\t\tSTATE1", state1) if state1 == 0: print("[DEBUG] state1 is 0") break conn.trigger(actions[action1]) print("\tCLIENT ACTION", actions[action1]) state2 = states.index(conn.state) print("\t\tSTATE2", state2) act = serv.server_action(state2) print("\tSERVER ACTION", server_actions[act]) conn.trigger(server_actions[act]) new_state = states.index(conn.state) if new_state != state2: print("\t[DEBUG]: Server changed state from ", state2, "to", new_state) state2 = new_state tmp_reward, done = compute_reward(state1, state2, action1) # Choosing the next action action2 = self.choose_action(state2, actions, Q) # Learning the Q-value self.update(state1, state2, tmp_reward, action1, action2, states, actions, Q, E) # Update log file with open(log_filename, "a") as write_file: write_file.write("\nTimestep " + str(t) + " finished.") write_file.write(" Temporary reward: " + str(tmp_reward)) write_file.write(" Previous state: " + str(state1)) write_file.write(" Current state: " + str(state2)) write_file.write(" Performed action: " + str(action1)) if self.algorithm != 'qlearning': write_file.write(" Next action: " + str(action2)) state1 = state2 action1 = action2 # Updating the respective vaLues t += 1 reward_per_episode += tmp_reward print("\t[DEBUG]: TMP REWARD", tmp_reward) print("\t[DEBUG]: REW PER EP", reward_per_episode) # If at the end of learning process if done: break y_timesteps.append(t - 1) y_reward.append(reward_per_episode) cum_reward += reward_per_episode y_cum_reward.append(cum_reward) with open(log_filename, "a") as write_file: write_file.write("\nEpisode " + str(episode) + " finished.\n") with open(output_filename, mode="a") as output_file: output_writer = csv.writer(output_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) output_writer.writerow( [episode, reward_per_episode, cum_reward, t - 1]) # Episode or episode+1? if self.follow_policy and episode % 20 == 0: finPolicy, finReward = follow_final_policy(Q) x_global.append(episode) y_global_reward.append(finReward) # Print and save the Q-matrix inside output_Q_data.csv file print("Q MATRIX:") print(Q) header = ['Q'] # For correct output structure for i in actions: header.append(i) with open(output_Q_filename, "w") as output_Q_file: output_Q_writer = csv.writer(output_Q_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_NONE) output_Q_writer.writerow(header) for index, stat in enumerate(states): row = [stat] for val in Q[index]: row.append("%.4f" % val) output_Q_writer.writerow(row) with open(log_filename, "a") as write_file: write_file.write("\nTotal time of %s seconds." % (time.time() - start_time)) # Visualizing the Q-matrix if not self.disable_graphs: print(actions) print(Q) print("--- %s seconds ---" % (time.time() - start_time)) plt.plot(x, y_reward) plt.xlabel('Episodes') plt.ylabel('Reward') plt.title('Rewards per episode') plt.show() plt.plot(x, y_timesteps) plt.xlabel('Episodes') plt.ylabel('Timestep to end of the episode') plt.title('Timesteps per episode') plt.show() optimal = [ 1, 2, 4, 2, 0 ] # client actions. How can i evaluate the policy if that depends on server actions? optimal_path = [1, 4, 5, 6, 10, 11, 12, 13, 0] sub_optimal_path1 = [1, 4, 5, 6, 10, 14, 15, 13, 0] sub_optimal_path2 = [1, 2, 3, 6, 10, 14, 15, 13, 0] sub_optimal_path3 = [1, 2, 3, 6, 10, 11, 12, 13, 0] finalPolicy, finalReward = follow_final_policy(Q) print("Length final policy is", len(finalPolicy)) print("Final policy is", finalPolicy) print("Final reward is", finalReward) return x_global, y_global_reward
def main(): args = parse_args() # Set the random seed if provided (affects client sampling, and batching) random.seed(1 + args.seed) np.random.seed(12 + args.seed) tf.set_random_seed(123 + args.seed) model_path = '%s/%s.py' % (args.dataset, args.model) if not os.path.exists(model_path): print('Please specify a valid dataset and a valid model.') model_path = '%s.%s' % (args.dataset, args.model) print('############################## %s ##############################' % model_path) # todo tdye model_info = {'model_path': model_path} # mod = importlib.import_module(model_path) # ClientModel = getattr(mod, 'ClientModel') tup = MAIN_PARAMS[args.dataset][args.t] num_rounds = args.num_rounds if args.num_rounds != -1 else tup[0] eval_every = args.eval_every if args.eval_every != -1 else tup[1] clients_per_round = args.clients_per_round if args.clients_per_round != -1 else tup[ 2] # Suppress tf warnings tf.logging.set_verbosity(tf.logging.WARN) # Create 2 models # model_params = (0.0003, 62) # 默认学习率 model_params = MODEL_PARAMS[model_path] # 重置学习率 # 重置后的模型参数 if args.lr != -1: model_params_list = list(model_params) model_params_list[0] = args.lr model_params = tuple(model_params_list) # Create client model, and share params with server model # 重置全局默认图 tf.reset_default_graph() # model_params (0.06, 62) # client_model = ClientModel(args.seed, *model_params) model_info.update({'seed': args.seed, 'model_params': model_params}) # Create server server = Server(model_info) # Create clients clients = setup_clients(args.dataset, model_info, args.use_val_set) client_ids, client_groups, client_num_samples = server.get_clients_info( clients) print('Clients in Total: %d' % len(clients)) # Initial status print('--- Random Initialization ---') stat_writer_fn = get_stat_writer_function(client_ids, client_groups, client_num_samples, args) sys_writer_fn = get_sys_writer_function(args) print_stats(0, server, clients, client_num_samples, args, stat_writer_fn, args.use_val_set) # Simulate training for i in range(num_rounds): print('--- Round %d of %d: Training %d Clients ---' % (i + 1, num_rounds, clients_per_round)) # Select clients to train this round server.select_clients(i, online(clients), num_clients=clients_per_round) c_ids, c_groups, c_num_samples = server.get_clients_info( server.selected_clients) # Simulate server model training on selected clients' data sys_metrics = server.train_model(num_epochs=args.num_epochs, batch_size=args.batch_size, minibatch=args.minibatch) sys_writer_fn(i + 1, c_ids, sys_metrics, c_groups, c_num_samples) # Update server model server.update_model() # Test model if (i + 1) % eval_every == 0 or (i + 1) == num_rounds: print_stats(i + 1, server, clients, client_num_samples, args, stat_writer_fn, args.use_val_set) # Save server model ckpt_path = os.path.join('checkpoints', args.dataset) if not os.path.exists(ckpt_path): os.makedirs(ckpt_path) save_path = server.save_model( os.path.join(ckpt_path, '{}.ckpt'.format(args.model))) print('Model saved in path: %s' % save_path) # Close models server.close_model()
player = lobby.whos_turn() owner = lobby.current_owner combo = lobby.current_combo msg = "It's your turn. <@{}>".format(player) if combo == None: msg += "\nIt's free to throw." await ctx.send(msg) # Constants TOKEN = get_token() RETRY_DELAY = 60 MAX_NUMBER = 26 # Server object for lobbies SERVER = Server("BigTwo") STATS = Stats() stats = STATS.read_stats_file() # Instantiate bot and set command prefix bot = commands.Bot(command_prefix="-") # Events @bot.event async def on_ready(): activity = discord.Game(name="-help", type=4) await bot.change_presence(status=discord.Status.online, activity=activity) print("BigTwo bot is up...") # Remove build-in command
from bus import MessageBus from server import Server from interface import UserInterface import sys if __name__ == '__main__': ip, port1, port2 = sys.argv[1:4] bus = MessageBus() server = Server(bus) app = UserInterface(bus) server.start(ip, port1, port2) app.show()
'-ad', required=True, help='Address of the server') parser.add_argument('--port', '-p', required=True, help='Port to listen') ### Optionnal parameters parser.add_argument('--timeout', '-t', required=False, help='Timeout of the server') ## Get parameters in variables args = vars(parser.parse_args()) address = args.pop('address') port = args.pop('port') timeout = args.pop('timeout') ### Init of socket server = Server(address, port, timeout) server.begin_listen() # socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # try: # socket.bind((address, port)) # print('Server bind to {}:{}'.format(address, port)) # except: # print('Server not able to bind to {}:{}'.format(address, port)) # # if timeout: # socket.settimeout(timeout) # else: # socket.settimeout(2)
import socket import threading from queue import Queue from server import Server if __name__ == "__main__": while True: port_num = input("Port? ") try: port_num = int(port_num) break except ValueError: pass Server('localhost',port_num).run()
last_server = self.create_new_server_for_user() last_server.append_user(User(self.total_ticks)) def handle_server(self, server): # tick, and remove if necessary, all the server's users server.tick_users() if server.is_empty(): # before we remove this server, calculate it's cost self.total_cost += server.ticks * Server.COST_PER_TICK self.servers.remove(server) else: server.tick() if __name__ == "__main__": main = Main(4, 2, [1, 3, 0, 1, 0, 1], [Server(2)]) tick = 0 while len(main.servers) > 0 or tick < len(main.users_per_tick): if tick < len(main.users_per_tick): for _ in range(main.users_per_tick[tick]): main.handle_new_user() total_users = [] # To avoid changing the list in place _servers = main.servers.copy() for server in _servers: main.handle_server(server) # Edge case for no more servers are available if len(server.users) > 0 or len(main.servers) == 0: total_users.append(str(len(server.users)))
#!/usr/bin/env python from server import Server def simple_output(request): output = {} output['headers'] = { "status": '200 OK', "version": "HTTP/1.1", "content-type": "text/html", } output["response"] = '<html><head></head><form action="/" method="POST"><input type=text /><input type=submit value=Submit /></form></html>' return output if __name__ == "__main__": s = Server() s.serve_requests(simple_output)
def create_new_server_for_user(self): new_server = Server(self.total_of_users_per_server) self.servers.append(new_server) return new_server
def read_input(self): with open(self.input_filepath, "r") as input_file: for line in input_file: if len(line) == 0: continue match = None for type, regex in Master.VALID_INPUTS.items(): match = re.match(regex, line) if match and type == "start_server": self.server = Server(match.group("addr"), int(match.group("port")), self.input_filepath) self.server.start() time.sleep(0.5) break elif match and type == "start_client": assert self.server is not None, "Server has not been started, cannot start a client before server" index = int(match.group("index")) assert 0 <= index <= 9, "Index must be an integer between 0 and 9, inclusive" if index not in self.clients_sending_message_threads: self.clients_sending_message_threads[index] = [] self.clients[index] = Client( index, match.group("server_addr"), int(match.group("server_port"))) self.clients[index].start() time.sleep(0.5) break elif match and type == "stop_server": self.server.stop() break elif match and type == "stop_client": index = int(match.group("index")) client_sending_message_threads = self.clients_sending_message_threads[ index] max_time = Master.MAX_TIME_STOP_CLIENT_WAITS_FOR # seconds while any([ x.isAlive() for x in client_sending_message_threads ]): max_time -= 0.1 if max_time == 0: raise Exception("Timeout on stop_client") time.sleep(0.1) self.clients[index].stop() break elif match and type == "set_buffer": index = int(match.group("index")) amt = int(match.group("size")) num_messages = int(match.group("num_recvs")) self.server.set_buffer_size(index, amt, num_messages) break elif match and type == "client_msg": index = int(match.group("index")) num_characters = int(match.group("num_characters")) message = self.generate_message_1( index, num_characters, self.input_filepath) assert index in self.clients, "Client {} has not been started, cannot send a message".format( index) # Note that we need to create a thread here to run the client.send_message method or else this # would block on client.send_message(message) until the message is fully sent t = threading.Thread( target=self.clients[index].send_message, args=[message]) self.clients_sending_message_threads[index].append(t) t.start() break elif match and type == "wait": time.sleep(float(match.group("seconds"))) break if match is None: raise Exception("'{}' is not a valid input in {}".format( line, self.input_filepath))
def main(): service_server = Server( address = Config.server_address, port = Config.server_port ) service_server.run()
from server import Server app_server = Server() app_server.run()
def dados_servidor(self): servidor = Server('', '', psutil.cpu_percent(), psutil.virtual_memory()[2]) return servidor
from server import Server server = Server() server.start()
from server import Server from config import vk_api_token, vk_group_id server1 = Server(vk_api_token, vk_group_id, "BruhBot") print('Запуск бота..') server1.send_to_subs() server1.start()
def run_server(levelname, port): commands = True if commands: input_queue = util.async_input() level = editor.load_file(levelname) world = create_world(level) server = Server(world, level.get('client_script', None), port) clock = [pygame.time.Clock, Clock][sys.platform.startswith('linux')]() did_crash = True try: while True: if commands: try: line = input_queue.get_nowait() except queue.Empty: pass else: line = line.strip() contents = line.split() if line == 'r': world = create_world(level) server.set_world(world, level.get('client_script', None)) print('Refreshing level') elif line == 'q': break elif len(contents) > 0 and contents[0] == 'l': if len(contents) != 2: print('Invalid number of arguments') else: levelname = contents[1] try: level = editor.load_file(levelname) except FileNotFoundError: print('Level doesn\'t exist') else: world = create_world(level) server.set_world(world, level.get('client_script', None)) elif line == 'p': if server.paused: print('Unpausing Server') else: print('Pausing Server') server.paused = not server.paused elif line == 's': if len(server.connections) != 0: for connection, players in server.connections.items(): print(', '.join(player.name for player in players) + ': ping={:.2f}±{:.2f}ms loss={:.1f}%'.format(connection.rtt*1000, connection.rtt_dev*1000, connection.packet_loss*100)) else: print('No players') else: print('Invalid command') server.update() #clock.tick() clock.tick(60) did_crash = False finally: if did_crash: server.stop('Server crashed') else: print('Stopping server') server.stop('Server stopped')
from server import Server from server.html_template import HTML_Template HOST = "127.0.0.1" PORT = 80 server = Server(HOST, PORT) index = HTML_Template("templates/index.html") contact_me = HTML_Template("templates/contact_me.html") server.add_page("/", index.generate_html()) server.add_page("/contact_me", contact_me.generate_html()) server.start_server() server.stop_server()
def configure(self, configuration_file): """ Configure the component instances list Keyword arguments: configuration_file - JSON configuration file to parse """ with open(configuration_file) as data_file: root = json.load(data_file) self.context = zmq.Context() for instance in root["Component Instances"]: instance_source = instance["Definition"] module_name, class_name = instance_source.split(".") module = importlib.import_module(module_name) component_instance = getattr(module, class_name)() component_instance.name = instance["Name"] publishers_config_map = {} subscribers_config_map = {} clients_config_map = {} servers_config_map = {} if "Timers" in instance.keys(): for timer in instance["Timers"]: timer_name = timer["Name"] timer_priority = timer["Priority"] timer_period = timer["Period"] timer_operation = timer["Function"] new_timer = Timer( timer_name, timer_priority, timer_period, component_instance. timer_functions[timer_operation], component_instance.operation_queue) component_instance.add_timer(new_timer) if "Publishers" in instance.keys(): for publisher in instance["Publishers"]: publisher_name = publisher["Name"] for endpoint in publisher["Endpoints"]: if publisher_name not in publishers_config_map.keys( ): publishers_config_map[publisher_name] = [] publishers_config_map[publisher_name].append( endpoint) new_publisher = Publisher( publisher_name, self.context) component_instance.add_publisher(new_publisher) if "Subscribers" in instance.keys(): for subscriber in instance["Subscribers"]: subscriber_name = subscriber["Name"] subscriber_priority = subscriber["Priority"] subscriber_filter = subscriber["Filter"] subscriber_operation = subscriber["Function"] for endpoint in subscriber["Endpoints"]: if subscriber_name not in subscribers_config_map.keys( ): subscribers_config_map[subscriber_name] = [] subscribers_config_map[subscriber_name].append( endpoint) new_subscriber = Subscriber(subscriber_name, subscriber_priority, self.context, subscriber_filter, subscribers_config_map[subscriber_name], component_instance.\ subscriber_functions[subscriber_operation], component_instance.operation_queue) component_instance.add_subscriber( new_subscriber) if "Clients" in instance.keys(): for client in instance["Clients"]: client_name = client["Name"] for endpoint in client["Endpoints"]: if client_name not in clients_config_map.keys(): clients_config_map[client_name] = [] clients_config_map[client_name].append( endpoint) new_client = Client(client_name, self.context) component_instance.add_client(new_client) if "Servers" in instance.keys(): for server in instance["Servers"]: server_name = server["Name"] server_priority = server["Priority"] server_operation = server["Function"] for endpoint in server["Endpoints"]: if server_name not in servers_config_map.keys(): servers_config_map[server_name] = [] servers_config_map[server_name].append( endpoint) new_server = Server( server_name, server_priority, self.context, servers_config_map[server_name], component_instance. server_functions[server_operation], component_instance.operation_queue) component_instance.add_server(new_server) component_instance.configure_publishers(publishers_config_map) component_instance.configure_subscribers( subscribers_config_map) component_instance.configure_clients(clients_config_map) component_instance.configure_servers(servers_config_map) self.component_instances.append(component_instance)
def create_server(self): server = Server("test_pseudo", "127.0.0.1", []) return server
# Импортируем созданный нами класс Server from server import Server # Получаем из config.py наш api-token from config import vk_api_token server1 = Server('тут токен', 'тут id', "server1") server1.test() def start(self): for event in self.long_poll.listen(): print(event)
keyboard_control = False camera_active = True cubesensor_active = False usfs_active = False arm_active = False autonomous = False # ---------------- Initialize Server ----------------- if server_online: # Set the client to the server's IP and PORT address #IP = '192.168.2.2' IP = '192.168.2.2' PORT = 20001 server = Server(IP, PORT) server.start() server.receiveConnection() print('Connection Received') # ----------------- Initialize Sonar ----------------- if sonars_activated: s_front = Sonar(6, 18) s_left = Sonar(5, 17) s_right = Sonar(12, 27) #s_backright = Sonar(13, 22) #s_backleft = Sonar(16, 23)