예제 #1
0
    def sendClientData(self, client, address, current_id):
        killSwitch = 0
        try:
            while killSwitch == 0:
                time.sleep(const.DELAY)
                if killSwitch == 1:
                    break
                if len(self.emergencyDict) > 0:
                    for x in self.emergencyDict:
                        client.send(self.emergencyDict[x])
                    logger.debug('emergency activated')
                else:
                    pass

                if len(self.client_dict[current_id]['main_data']) > 0:

                    for x in self.client_dict[current_id]['main_data']:
                        logger.debug(self.client_dict[current_id]['main_data'])
                        client.send(x)
                        print('\n' + 'sent ' + str(x) + ' to ' + str(address) +
                              '\n')
                        self.client_dict[current_id]['main_data'].remove(x)

                else:
                    client.send(Serializer().serializerRoot(
                        RequestCOTController().ping(
                            eventuid=uuid.uuid1())).encode())
            client.shutdown(socket.SHUT_RDWR)
            client.close()
        except Exception as e:
            logger.warning('error in send info ' + str(e))
            client.close()
            return 1
예제 #2
0
    def sendClientData(self, client, address, current_id):
        killSwitch = 0
        try:
            while killSwitch == 0:
                time.sleep(const.DELAY)
                if killSwitch == 1:
                    break
                if len(self.emergencyDict) > 0:
                    for x in self.emergencyDict:
                        client.send(self.emergencyDict[x])
                else:
                    logger.debug('emergency not found')

                if len(self.client_dict[current_id]['main_data']) > 0:

                    for x in self.client_dict[current_id]['main_data']:
                        print('sending' + str(client))
                        client.send(x)
                        print('\n' + 'sent ' + str(x) + ' to ' + str(address) +
                              '\n')
                        self.client_dict[current_id]['main_data'].remove(x)
                        logger.debug('sending ' + str(x) + ' to ' +
                                     str(client))
                else:
                    print('sending' + str(client))
                    client.send(Serializer().serializerRoot(
                        RequestCOTController().ping()).encode())
            client.close()
        except Exception as e:
            logger.warning('error in send info ' + str(e))
            client.close()
예제 #3
0
 def bandaid(self):
     while True:
         start = datetime.datetime.now()
         end = start + datetime.timedelta(minutes=const.RENEWTIME)
         while datetime.datetime.now() < end:
             time.sleep(10)
         self.bandaidUID = uuid.uuid1()
         mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         mysock.connect(('127.0.0.1', const.DEFAULTPORT))
         mysock.send(Serializer().serializerRoot(
             RequestCOTController().ping(
                 eventuid=self.bandaidUID)).encode())
         mysock.recv(2048)
         mysock.shutdown(socket.SHUT_RDWR)
         mysock.close()
         logger.info('finished bandaid keepalive')
         logger.info('nuber of threads is ')
         logger.info(threading.enumerate())
예제 #4
0
    def sendClientData(self, client, address, current_id):
        try:
            while True:
                time.sleep(const.DELAY)
                for uid in self.emergencyDict:
                    client.send(self.emergencyDict[uid])
                    logger.info(f"Emergency activated: {uid}")

                if len(self.client_dict[current_id]['main_data']) > 0:
                    for x in self.client_dict[current_id]['main_data']:
                        logger.debug(self.client_dict[current_id]['main_data'])
                        client.send(x)
                        logger.info('Sent ' + str(x) + ' to ' + str(address))
                        self.client_dict[current_id]['main_data'].remove(x)
                else:
                    client.send(Serializer().serializerRoot(
                        RequestCOTController().ping(
                            eventuid=uuid.uuid1())).encode())
        except:
            logger.error(traceback.format_exc())
            logger.warning('Error in sendClientData')
        finally:
            client.close()
예제 #5
0
 def bandaid(self):
     while True:
         try:
             start = datetime.datetime.now()
             end = start + datetime.timedelta(minutes=const.RENEWTIME)
             while datetime.datetime.now() < end:
                 time.sleep(10)
             self.bandaidUID = uuid.uuid1()
             mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
             mysock.connect(('127.0.0.1', const.PORT))
             mysock.send(Serializer().serializerRoot(
                 RequestCOTController().ping(
                     eventuid=self.bandaidUID)).encode())
             mysock.recv(2048)
             mysock.shutdown(socket.SHUT_RDWR)
             mysock.close()
             logger.info('finished bandaid keepalive')
             logger.debug(
                 f"Currently running {len(threading.enumerate())} threads")
         except ConnectionRefusedError:
             logger.warning("Bandaid listening socket was closed")
         except:
             logger.error(traceback.format_exc())
             logger.error("Error in bandaid()")
예제 #6
0
    def listenToClient(self, client, address):
        ''' 
        Function to receive data from the client. this must be long as everything
        '''
        try:
            defaults = self.connectionSetup(client, address)
            if defaults == 'error':
                client.shutdown(socket.SHUT_RDWR)
                client.close()
                return
            elif defaults == 'Bandaid':
                self.sock.shutdown(socket.SHUT_RDWR)
                client.close()
                return
            else:
                defaults = defaults.split(' ? ')
                logger.debug(defaults)
                first_run = int(defaults[0])
                id_data = bytes(defaults[2], 'utf-8')
                current_id = int(defaults[3])
                # main connection loop
                while True:
                    # Receive data
                    try:
                        if first_run == 0:
                            data = self.recieveAll(client)
                            logger.debug(
                                f"Received data from client: {str(data)}")
                            working = self.check_xml(data, current_id)
                            # checking if check_xml detected client disconnect
                            if working == const.FAIL:
                                timeoutInfo = Serializer().serializerRoot(
                                    RequestCOTController().timeout(
                                        eventhow='h-g-i-g-o',
                                        eventuid=uuid.uuid1(),
                                        linkuid=self.client_dict[current_id]
                                        ['uid']))
                                logger.debug(
                                    f"Sending timeout: {timeoutInfo.encode()}")
                                for client_id in self.client_dict:
                                    if client_id != current_id:
                                        self.client_dict[client_id][
                                            'client'].send(
                                                timeoutInfo.encode())
                                uid = self.client_dict[current_id]['uid']
                                del self.client_dict[current_id]
                                with sqlite3.connect(const.DATABASE) as db:
                                    cursor = db.cursor()
                                    cursor.execute(sql.DELETEBYUID, (uid, ))
                                    cursor.close()
                                    db.commit()
                                    client.shutdown(socket.SHUT_RDWR)
                                    client.close()
                                return
                            elif working == const.PING:
                                logger.debug('Received ping')

                        elif first_run == 1:
                            for client_id in self.client_dict:
                                client = self.client_dict[client_id]['client']
                                if client != self.client_dict[current_id][
                                        'client']:
                                    logger.info('Sending ' + str(id_data))
                                    client.send(self.client_dict[current_id]
                                                ['id_data'])
                            for client_id in self.client_dict:
                                data = self.client_dict[client_id]['id_data']
                                logger.debug('Sending conn data to ' +
                                             str(client))
                                client.send(data)
                            threading.Thread(target=self.sendClientData,
                                             args=(client, address,
                                                   current_id),
                                             daemon=True).start()

                        # just some debug stuff
                        first_run = 0
                    except:
                        logger.error(traceback.format_exc())
                        logger.error('Error in listenToClient() main loop')
                        client.close()
                        return
        except Exception as e:
            logger.error(traceback.format_exc())
            logging.error("Unknown error in listenToClient")
            client.close()
예제 #7
0
파일: server.py 프로젝트: ConorBeh/TAKlib
    def listenToClient(self, client, address):
        ''' 
		Function to receive data from the client. this must be long as everything
		'''
        defaults = self.connectionSetup(client, address)
        defaults = defaults.split(' ? ')
        print(defaults)
        first_run = defaults[0]
        total_clients_connected = defaults[1]
        id_data = defaults[2]
        current_id = defaults[3]
        first_run = int(first_run)
        total_clients_connected = int(total_clients_connected)
        id_data = bytes(id_data, 'utf-8')
        current_id = int(current_id)
        #main connection loop
        killSwitch = 0
        while killSwitch == 0:
            #recieve data

            try:
                if first_run == 0:
                    data = self.recieveAll(client)
                    logging.debug('recieved ' + str(data) + ' from ' +
                                  str(self.client_dict[current_id]['uid']))
                    working = self.check_xml(data, current_id)
                    #checking if check_xml detected client disconnect
                    if working == const.FAIL:
                        print('here')
                        timeoutInfo = Serializer().serializerRoot(
                            RequestCOTController().timeout(
                                linkuid=self.client_dict[current_id]['uid']))
                        if len(self.client_dict) > 0:

                            for x in self.client_dict:

                                if x != current_id:
                                    print(self.client_dict[x]['client'])
                                    self.client_dict[x]['client'].send(
                                        timeoutInfo.encode())

                                else:
                                    pass
                        else:
                            pass
                        del self.client_dict[current_id]
                        client.close()
                        break
                    else:
                        pass

                elif first_run == 1:
                    print('something \n')
                    for x in self.client_dict:
                        data = self.client_dict[x]['id_data']
                        logging.debug('sending conn data abc' +
                                      str(self.client_dict[x]['id_data']) +
                                      'to ' + str(client) + '\n')
                        client.send(data)

                #just some debug stuff
                first_run = 0
            except Exception as e:
                logging.warning('error in main loop ' + str(e))
예제 #8
0
    def listenToClient(self, client, address):
        ''' 
		Function to receive data from the client. this must be long as everything
		'''
        try:
            defaults = self.connectionSetup(client, address)
            if defaults == 'error':
                client.shutdown(socket.SHUT_RDWR)
                client.close()
                return 1
            elif defaults == 'Bandaid':
                self.sock.shutdown(socket.SHUT_RDWR)
                client.close()
                return 1
            else:
                defaults = defaults.split(' ? ')
                print(defaults)
                first_run = defaults[0]
                id_data = defaults[2]
                current_id = defaults[3]
                first_run = int(first_run)
                id_data = bytes(id_data, 'utf-8')
                current_id = int(current_id)
                #main connection loop
                killSwitch = 0
                while killSwitch == 0:
                    #recieve data

                    try:
                        if first_run == 0:
                            data = self.recieveAll(client)
                            logger.debug(data)
                            working = self.check_xml(data, current_id)
                            #checking if check_xml detected client disconnect
                            if working == const.FAIL:
                                timeoutInfo = Serializer().serializerRoot(
                                    RequestCOTController().timeout(
                                        eventhow='h-g-i-g-o',
                                        eventuid=uuid.uuid1(),
                                        linkuid=self.client_dict[current_id]
                                        ['uid']))
                                print(timeoutInfo.encode())
                                logger.debug('sending timeout information')
                                if len(self.client_dict) > 0:

                                    for x in self.client_dict:

                                        if x != current_id:
                                            self.client_dict[x]['client'].send(
                                                timeoutInfo.encode())

                                        else:
                                            pass
                                else:
                                    pass
                                uid = self.client_dict[current_id]['uid']
                                del self.client_dict[current_id]
                                sqliteServer = sqlite3.connect(const.DATABASE)
                                cursor = sqliteServer.cursor()
                                cursor.execute(sql.DELETEBYUID, (uid, ))
                                sqliteServer.commit()
                                cursor.close()
                                sqliteServer.close()
                                client.shutdown(socket.SHUT_RDWR)
                                client.close()
                                break
                            elif working == const.PING:
                                logger.debug('recieved ping')

                            else:
                                pass

                        elif first_run == 1:
                            print('something \n')
                            for x in self.client_dict:
                                client = self.client_dict[x]['client']
                                if client != self.client_dict[current_id][
                                        'client']:
                                    print('sending' + str(id_data))
                                    print(id_data)
                                    client.send(self.client_dict[current_id]
                                                ['id_data'])
                                else:
                                    pass
                            for x in self.client_dict:
                                data = self.client_dict[x]['id_data']
                                logger.debug(
                                    'sending conn data ' +
                                    str(self.client_dict[x]['id_data']) +
                                    'to ' + str(client) + '\n')
                                client.send(data)
                            threading.Thread(target=self.sendClientData,
                                             args=(client, address,
                                                   current_id),
                                             daemon=True).start()

                        #just some debug stuff
                        first_run = 0
                    except Exception as e:
                        logger.warning('error in main loop')
                        logger.warning(str(e))
                        client.close()
                        killSwitch = 1
                        return 1
        except Exception as e:
            client.close()
            return 1
예제 #9
0
    def listenToClient(self, client, address):
        ''' 
		Function to receive data from the client. this must be long as everything
		'''
        defaults = self.connectionSetup(client, address)
        defaults = defaults.split(' ? ')
        print(defaults)
        first_run = defaults[0]
        id_data = defaults[2]
        current_id = defaults[3]
        first_run = int(first_run)
        id_data = bytes(id_data, 'utf-8')
        current_id = int(current_id)
        #main connection loop
        killSwitch = 0
        while killSwitch == 0:
            #recieve data

            try:
                if first_run == 0:
                    data = self.recieveAll(client)
                    logger.debug('recieved ' + str(data) + ' from ' +
                                 str(self.client_dict[current_id]['uid']))
                    working = self.check_xml(data, current_id)
                    #checking if check_xml detected client disconnect
                    if working == const.FAIL:
                        print('here')
                        timeoutInfo = Serializer(
                        ).serializerRoot(RequestCOTController().timeout(
                            eventhow='h-g-i-g-o',
                            eventuid='aef53602-ea19-4a82-a07b-f0069470b23d',
                            linkuid=self.client_dict[current_id]['uid']))
                        print(timeoutInfo.encode())
                        logger.debug(timeoutInfo.encode())
                        logger.debug('timeout info is with utf8 ' +
                                     str(timeoutInfo))
                        logger.debug('timeout info is with ascii ' +
                                     str(bytes(timeoutInfo, 'utf-8')))
                        if len(self.client_dict) > 0:

                            for x in self.client_dict:

                                if x != current_id:
                                    logger.debug(
                                        'sending timeout to ' +
                                        str(self.client_dict[x]['client']))
                                    self.client_dict[x]['client'].send(
                                        timeoutInfo.encode())

                                else:
                                    pass
                        else:
                            pass
                        del self.client_dict[current_id]
                        client.close()
                        break
                    else:
                        pass

                elif first_run == 1:
                    print('something \n')
                    for x in self.client_dict:
                        client = self.client_dict[x]['client']
                        if client != self.client_dict[current_id]['client']:
                            print('sending' + str(id_data))
                            print(id_data)
                            client.send(
                                self.client_dict[current_id]['id_data'])
                        else:
                            pass
                    for x in self.client_dict:
                        data = self.client_dict[x]['id_data']
                        logger.debug('sending conn data abc' +
                                     str(self.client_dict[x]['id_data']) +
                                     'to ' + str(client) + '\n')
                        client.send(data)

                #just some debug stuff
                first_run = 0
            except Exception as e:
                logger.warning('error in main loop')
                logger.warning(str(e))
                killSwitch = 1