Пример #1
0
def main():
    # Read options from command line
    opts = readOptions(sys.argv[1:])

    # Init peer
    mypeer = Peer(opts.id, opts.maxpeers, opts.port, opts.ttl, opts.verbose)

    # Add list of known peers
    for p in opts.peers:
        pfull = p.split(':')
        mypeer.addpeer(pfull[0], pfull[1], int(pfull[2]))

    # Add handlers
    for m in messages:
        mypeer.addhandler(m, messages[m].handler)

    # Add router
    mypeer.addrouter(distancerouter)

    # Start peer server in a separate thread
    t = threading.Thread( target = mypeer.start, args = [opts.backlog, opts.timeout] )
    t.daemon = True
    t.start()
    print(f'Peer {mypeer.host}:{mypeer.port} started')

    # Start client
    menu()
    try:
        for line in sys.stdin:
            line = line.rstrip().split(' ', 2)
            msgtype = line[0].upper()
            target = line[1]
            if msgtype not in messages or not messages[msgtype].iscallable:
                print('Wrong message type. Please try again.')
                continue
            data = ''
            if len(line) == 3:
                data = line[2]
            if messages[msgtype].isasync:
                # Need to add own info as sender for async messages, so receiver can respond
                data = json.dumps({'data': data, 'sender': mypeer.peerid})
            res = mypeer.sendtopeer(target, msgtype, data, not messages[msgtype].isasync)
            for r in res:
                if r[0] == 'ERRO':
                    print(f'{r[1]}')
                    break
                if r[0] == 'RESP':
                    print(f'[{target}] -> {r[1]}')
                    continue
                print('Unable to process response.')
                continue
            menu()

    except KeyboardInterrupt:
        exit()