def launch_client(clients_threads, client_id, client_data, routers_data, routers_threads): arp_table_mac = data.client_arp_table_generator(client_data["gateway_ip"], routers_data) default_gateway = client_data["gateway_ip"] # find the id of the router to which the server will connect for router, router_data in routers_data.items(): if (router_data["client_side"]["ip_address"] == default_gateway): router_id = router break router_thread = routers_threads[router_id] init_params = { "clients_threads": clients_threads, "arp_table_mac": arp_table_mac, "client_data": client_data, "client_id": client_id, "router_thread": router_thread, "router_id": router_id, "sync_event_message": sync_event_message, "sync_event_connection": sync_event_connection } client_thread = ClientThread(init_params) clients_threads[client_id] = client_thread client_thread.start()
def serve(self): worker_thread = Thread(target=self.tick) worker_thread.daemon = True worker_thread.start() while True: connection, address = self.socket_server.accept() connection.settimeout(const.SERVER_CONNECTION_TIMEOUT) log(f"Server - {address} connected") thread = ClientThread(connection, address, self) thread.daemon = True self.client_pool.append(thread) thread.start()
def wait_for_connect(self,client_args={}): (clientsocket, address) = self.serversocket.accept() self.logger.info("Starting client thread %s:%d" % address) commands = self._server_commands() args = dict(client_args) if args.has_key('commands'): args['commands'].update(commands) else: args['commands'] = commands ct = ClientThread(sock=clientsocket, address=address, logger=self.logger, args=args) ct.cleanup_func = self._client_stopped ct.broadcast_func = self._broadcast with self.lock: self.clientthreads.append(ct) ct.start()
if not q.empty(): r = q.get() if isinstance(r, MailDataFrame): print(r.data) else: for i in range(2): if r[-i] in ["\r", "\n"]: r = r[:-i] print(r) HOST = '127.0.0.1' SERVPORT = 42069 DESTPORT = 25 BACKLOG = 5 msg_q = Queue() log_q = Queue() client_thread = ClientThread((HOST, DESTPORT), msg_q, log_q, daemon=True) client_thread.start() log = Thread(target=logger, args=(log_q, ), daemon=True) log.start() with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, SERVPORT)) i = 0 while True: s.listen(BACKLOG) cl_skt, addr = s.accept() t = ServerThread(cl_skt, msg_q, log_q, daemon=True) t.start() i = i + 1
import sys if __name__ == "__main__": if len(sys.argv) > 1: if sys.argv[1] == "-c" or sys.argv[1] == "--cliente": # Se entrou aqui é porque deve subir um cliente if len(sys.argv) == 3: # Pega argumentos ip:porta da linha de comando server = sys.argv[2] server = server.split(":") # Cria thread cliente para ip:porta informados # na linha de comando server = ClientThread(server[0],server[1]) server.setName(THREAD_CLIENT) server.start() else: print "forneça ip:porta do servidor." elif sys.argv[1] == "-s" or sys.argv[1] == "--servidor": # Se entrou aqui é porque deve subir um servidor if len(sys.argv) == 3: # Pega argumento porta da linha de comando porta = sys.argv[2] # Cria thread servidor para port server = ServerThread(porta) server.setName(THREAD_SERVER) server.start() else: print "forneça uma porta para escutar."
class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) self.run = True self.mode = None # signals 'server'/'client' mode self.input_values = [] # input values retrieve from UI self.io_handlers() # initialize UI components # communication/network variables self.tcp_main_queue = Queue.Queue() self.tcp_sim_queue = Queue.Queue() self.thread_event = threading.Event() self.data = "meaningless" self.custom_data = '' self.cm = SceneManager(self.graphicsView) self.animations = [] self.animator = QTimer() # timer paired with main thread self.animator.timeout.connect(self.update) # timeout callback self.update() # initial call # links buttons to event handlers def io_handlers(self): self.btn_start_server.clicked.connect(self.startServer) self.btn_start_client.clicked.connect(self.startClient) self.btn_stop.clicked.connect(self.stopSimulation) self.btn_random_ball.clicked.connect(self.randomBall) self.btn_custom_ball.clicked.connect(self.customBall) # period callback used to animate 'graphicsView' def update(self): # moves item to location smoothly in one second def config_animate_to(t,item,x,y): # used to animate an item in specific ways animation = QGraphicsItemAnimation() # create a timeline (1 sec here) timeline = QTimeLine(100) timeline.setFrameRange(0,200) # 200 steps #item should at 'x,y' by time 't's animation.setPosAt(t,QPointF(x,y)) animation.setItem(item) # animate this item animation.setTimeLine(timeline) # with this duration/steps return animation if (self.run): # still running # check for items received via tcp if (not self.tcp_sim_queue.empty()): self.cm.deleteItems() # item = self.tcp_sim_queue.get() # retrieve value msg = self.tcp_sim_queue.get() if (type(msg) == type('s')) : # self.cm.addItem(item) # add new item self.cm.addItem(msg) else: self.cm.addItems(msg) elif (self.custom_data != ''): # data received from GUI # print 'self.custom_data is %s' % self.custom_data #DEBUG self.cm.addItem(self.custom_data) self.custom_data = '' if (str(self.mode) == 'SERVER'): del self.animations[:] # empty list of prev animations # retrieve all items in the graphicsView scene_items = self.cm.getItems() for item in scene_items: next_x, next_y = self.cm.next_move(item) # determine next location # create corresponding item animation (given displacement in local coordinates) item_animation = config_animate_to(1,item,next_x,next_y) self.animations.append(item_animation) # store item animation # update location values of item (global coordiantes) item.set_location(next_x+item.x_start,next_y+item.y_start) # signal the start of all animations [ animation.timeLine().start() for animation in self.animations] # send all simulation items to server thread if (len(scene_items) > 0): # retrieve items encoded for TCP tcp_list = self.cm.getItemsForTCP() # print ('Observed: ' + str(tcp_list)) #DEBUG self.tcp_main_queue.put(tcp_list) self.animator.start(ANIMATOR_TIMEOUT) def startServer(self): self.btn_start_client.setEnabled(False) # disable 'client' button # initiate server thread and pass GUI/simulation messgae queues self.mode = ServerThread(self.tcp_main_queue,self.thread_event) self.mode.daemon = True self.mode.start() def startClient(self): try: # initiate client thread and pass simulation GUI message queue self.mode = ClientThread(self.tcp_sim_queue,self.thread_event) self.mode.daemon = True # thread to close when main thread closes self.mode.start() # disable all buttons except 'Stop' self.btn_start_server.setEnabled(False) self.btn_start_client.setEnabled(False) self.btn_random_ball.setEnabled(False) self.btn_custom_ball.setEnabled(False) except Exception: print "No server available." def stopSimulation(self): # disable all buttons self.btn_start_server.setEnabled(False) self.btn_start_client.setEnabled(False) self.btn_stop.setEnabled(False) self.btn_random_ball.setEnabled(False) self.btn_custom_ball.setEnabled(False) self.run = False self.thread_event.set() print 'Main thread stopped' def randomBall(self): # select random radius, mass, x/y velocities mass = random.randint(5, 20) radius = int(mass * 2) x_vel = random.randint(1,30) y_vel = random.randint(1,30) # select x/y positions within graphicsView x_pos = random.randint(0,SCENE_WIDTH-radius) y_pos = random.randint(0,SCENE_HEIGHT-radius) # encode data for TCP transport self.data = 'x' + str(x_pos) + 'y' + str(y_pos) + 'xv' + str(x_vel) + \ 'yv' + str(y_vel) + 'm' + str(mass) + 'r' + str(radius) # self.tcp_main_queue.put(self.data) # self.tcp_sim_queue.put(self.data) self.custom_data = self.data def customBall(self): # create dialog for input dialog = CustomDialog() # retrieve input from dialog if (dialog.exec_()): self.input_values = dialog.results params = ['x','y','xv','yv','m','r'] self.data = '' # encode data for TCP transmission for i in range(0,len(self.input_values)): self.data += params[i] + str(self.input_values[i]) # # input in queue for tcp thread if (len(self.data) > 0): self.custom_data = self.data
def join_server(self, ip): ip = self.sender().ip.text() client = ClientThread(ip) client.start()