def __init__(self, screen, clock, server_connection=None): self.s_conn = ClientConnection(self, server_connection) self.screen = screen self.clock = clock self.playing = True self.assets = list() self.load_assets() self.grid = [ list([None] * ARENA_TILE_WIDTH) for i in range(ARENA_TILE_HEIGHT) ] ########################################################### ########################################################### # Sprites self.all_sprites = pg.sprite.Group() self.structures = pg.sprite.Group() self.defences = pg.sprite.Group() self.attackers = pg.sprite.Group() self.projectiles = pg.sprite.Group() self.menu_items = pg.sprite.Group() self.menu = InGameMenu(self) self.defence_center = DefenceCenter(self) self.attack_center = AttackCenter(self) self.null_focus = Unit(self) self.menu.set_focus(self.null_focus) ########################################################### # CIRCLE REFERENCE # ########################################################### self.menu.ready_btn.set_action(self.attack_center.set_ready)
def enter_main_loop(self): try: while True: (client_socket, address) = self.server_socket.accept() print(address[0] + ':' + str(address[1]) + " connected.") client_connection = ClientConnection(self, client_socket, self.image_processor) self.clients_list.append(client_connection) threading.Thread( target=client_connection.enter_main_loop).start() except OSError: if not self.stop_running: # If not from us calling .stop() raise
def startClient(ip, port): fileName = input("Enter filename: ") # launch localhost client connecting to server sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(("0.0.0.0", random.randint(10000, 60000))) ch = ConnectionHandler(sock, 100, 0.1) # create connection streamID = random.randint(0, 2 ^ 32 - 1) c = ClientConnection((ip, port), ch, streamID, 100, 1, fileName) # client sends content to server ch.addConnection(c) ch.serve() print("File sent biatch!")
parser.add_argument('--verbose', help='Should display the game turn by turn', action='store_true') args = parser.parse_args() #Creates and connects the socket connection to the clients sock = socket.socket() host = 'localhost' sock.bind((host, args.port)) sock.settimeout(7) sock.listen(2) print('Waiting for client 1...') conn1, addr1 = sock.accept() if not args.verbose: conn1.settimeout(3) p1 = ClientConnection(conn1, 'p1', args.verbose) print('Waiting for client 2...') conn2, addr2 = sock.accept() if not args.verbose: conn2.settimeout(3) p2 = ClientConnection(conn2, 'p2', args.verbose) #Picks a random map from the maps folder and creates the game file_name = 'maps/{}'.format(random.choice(os.listdir('maps'))) game = GridFighters(p1, p2, open(file_name, 'r')) #Ticks the game unit there is a winner or the max_turns is reached turn = 0 winner = None
default=5) parser.add_argument("-i", "--input", help="File to send", default="tmp.file") args = parser.parse_args() server_ip = "127.0.0.1" server_port = 9002 sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM) #socketWrapper.perfectSocket(("localhost",9001)) # UDP sock.bind((server_ip, server_port)) ch = ConnectionHandler(sock, args.window, args.timeout) # get file to send fileName = "text.txt" # input("Enter file name: ") # create connection streamID = 1111 c = ClientConnection(("127.0.0.1", 9001), ch, streamID, args.window, args.timeout, fileName) # add connection ch.addConnection(c) try: ch.serve() except KeyboardInterrupt: ch.stop()
#! /usr/bin/python3 from client_game import Game from client_connection import ClientConnection from helpers import setup_logger import signal logger = setup_logger("settings.conf", "client") # create game object to server, connect automatically connection = ClientConnection() def handle_keyboard_interrupts(signum, frame): connection.close() logger.info("Exiting") exit(-1) def main(): """Main function of the client""" signal.signal(signal.SIGINT, handle_keyboard_interrupts) Game(connection).start() connection.close() logger.info("Exiting") if __name__ == "__main__": main()
class Game: def __init__(self, screen, clock, server_connection=None): self.s_conn = ClientConnection(self, server_connection) self.screen = screen self.clock = clock self.playing = True self.assets = list() self.load_assets() self.grid = [ list([None] * ARENA_TILE_WIDTH) for i in range(ARENA_TILE_HEIGHT) ] ########################################################### ########################################################### # Sprites self.all_sprites = pg.sprite.Group() self.structures = pg.sprite.Group() self.defences = pg.sprite.Group() self.attackers = pg.sprite.Group() self.projectiles = pg.sprite.Group() self.menu_items = pg.sprite.Group() self.menu = InGameMenu(self) self.defence_center = DefenceCenter(self) self.attack_center = AttackCenter(self) self.null_focus = Unit(self) self.menu.set_focus(self.null_focus) ########################################################### # CIRCLE REFERENCE # ########################################################### self.menu.ready_btn.set_action(self.attack_center.set_ready) def load_assets(self): self.background_image = pg.Surface((ARENA_WIDTH, ARENA_HEIGHT)) self.background_image.fill(BGCOLOUR) for i in range(70): pos_x = randint(TILE_SIZE, ARENA_WIDTH - TILE_SIZE) pos_y = randint(TILE_SIZE, ARENA_WIDTH - TILE_SIZE) size = randint(1, 3) pg.draw.circle(self.background_image, WHITE, (pos_x, pos_y), size) # FONTS def run(self): while self.playing: self.clock.tick(FPS) self.events() self.draw_background() self.update() self.communicate() self.draw() def quit(self): pg.quit() sys.exit() def communicate(self): self.s_conn.update() def update(self): # update portion of the game loop self.global_info = [ "[C] {} ({})".format(*self.defence_center.get_global_info()) ] self.all_sprites.update() def draw_background(self): self.screen.blit(self.background_image, (0, 0)) def draw(self): pg.display.set_caption("{:.2f}".format(self.clock.get_fps())) self.projectiles.draw(self.screen) self.structures.draw(self.screen) self.defences.draw(self.screen) self.attackers.draw(self.screen) self.menu_items.draw(self.screen) self.defence_center.draw_effects() pg.display.flip() def events(self): # catch all events here for event in pg.event.get(): if event.type == pg.QUIT: self.quit() if event.type == pg.KEYDOWN: if event.key == pg.K_1: self.menu.unit_info.unit_btns[0].run_action() if event.key == pg.K_2: self.menu.unit_info.unit_btns[1].run_action() if event.key == pg.K_3: self.menu.unit_info.unit_btns[2].run_action() if event.key == pg.K_4: self.menu.unit_info.unit_btns[3].run_action() if pg.mouse.get_pressed()[2]: self.defence_center.not_building() self.menu.set_focus(self.null_focus)
def start(self): log.error(DEBUG, msg='worker start') if CONFIG['chroot']: os.chroot(CONFIG['web_server_root']) os.setreuid(UID, UID) self._epoll.register(self._socket, select.EPOLLIN | select.EPOLLET) # self._profiler.mark_event_loop_begin_time() # self._profiler.mark_registering_begin() while True: # self._profiler.mark_event_loop_end() # self._profiler.mark_registering_end() log.error(DEBUG, msg='going to poll...') action_requests = self._epoll.poll() # self._profiler.mark_event_loop_begin_time() # self._profiler.mark_registering_begin() for fd, eventmask in action_requests: if fd == self._socket.fileno(): log.error(DEBUG, msg='accepting connections...') try: accepted_connections = 0 while True: try: log.error(DEBUG, msg='going to accept...') conn, addr = self._socket.accept() log.error(DEBUG, msg='conn accepted') except OSError as error: if error.errno == 0: # https://bugs.python.org/issue31122 log.error(DEBUG, msg='ERRNO 0') continue else: raise error except ssl.SSLError as error: log.error(DEBUG, msg='SSL error thrown at accept') log.error(DEBUG, msg=error) continue if accepted_connections > CONFIG[ 'accept_conn_limit']: conn.close() continue conn.setblocking(False) accepted_connections += 1 log.error(DEBUG, msg='connection accepted') log.error(DEBUG, var_name='conn', var_value=conn) log.error(DEBUG, var_name='addr', var_value=addr) self.register_activity( conn, select.EPOLLIN, self.req_handler(ClientConnection(conn, addr))) except OSError as error: if error.errno == errno.EMFILE: log.error(ERROR, msg=error) os._exit(os.EX_UNAVAILABLE) elif error.errno == errno.EWOULDBLOCK: log.error(DEBUG, msg='accept going to block') else: log.error(DEBUG, msg='OSError thrown at accept') log.error(DEBUG, msg=traceback.format_exc()) log.error(ERROR, msg=error) finally: log.error(DEBUG, msg='Accepted {0} connections'.format( accepted_connections)) else: assert fd in self._activity_iterators activity_iter = self._activity_iterators[fd] # self._profiler.mark_event_loop_end() # self._profiler.mark_registering_end() result = next(activity_iter, None) # self._profiler.mark_event_loop_begin_time() # self._profiler.mark_registering_begin() assert result is None or isinstance(result, tuple) # self._profiler.mark_registering_begin() if isinstance(result, tuple): assert len(result) == 2 log.error(DEBUG, msg=result) new_fd, new_eventmask = result # if (new_fd != fd or new_eventmask != eventmask): self.unregister_activity(fd) self.register_activity(new_fd, new_eventmask, activity_iter) else: self.unregister_activity(fd)