Beispiel #1
0
def test_wait_for_message_with_autoreply(support):
    address = nw0.core.address()
    reply_queue = queue.Queue()
    support.queue.put(
        ("wait_for_message_from_with_autoreply", [address, reply_queue]))
    nw0.wait_for_message_from(address, autoreply=True)
    assert reply_queue.get() == nw0.messenger.EMPTY
Beispiel #2
0
def main():

    username = input("Please enter your username: "******"zerochat_" + username)

    oldchats = {}
    while True:

        chats = {name:address for name, address in nw0.discover_all() if name.startswith("zerochat_")}
        if chats.keys() != oldchats.keys():
            print("New users:")
            print(chats)

        rlist, wlist, elist = select.select([sys.stdin], [], [], 0.1)
        if rlist:
            recipient = sys.stdin.readline().rstrip()
            msg = input("Message:").rstrip()
            print("\x1b[31;m[%s] %s\x1b[0m" % (recipient, msg))

            recipient_service = nw0.discover("zerochat_" + recipient)
            nw0.send_message_to(recipient_service, msg)


        received_msg = nw0.wait_for_message_from(address, wait_for_s=0, autoreply=True)
        if received_msg is not None:
            print("Got message: %s" % received_msg)

        oldchats = chats
Beispiel #3
0
def test_wait_for_message(support):
    address = nw0.core.address()
    message_sent = uuid.uuid4().hex
    support.queue.put(("wait_for_message_from", [address, message_sent]))
    message_received = nw0.wait_for_message_from(address, wait_for_s=5)
    assert message_received == message_sent
    nw0.send_reply_to(address, message_received)
Beispiel #4
0
def test_wait_for_message(support):
    address = nw0.core.address()
    message_sent = uuid.uuid4().hex
    support.queue.put(("wait_for_message_from", [address, message_sent]))
    message_received = nw0.wait_for_message_from(address, wait_for_s=5)
    assert message_received == message_sent
    nw0.send_reply_to(address, message_received)
Beispiel #5
0
def test_send_reply(support):
    address = nw0.core.address()
    reply_queue = queue.Queue()

    support.queue.put(("send_reply_to", [address, reply_queue]))
    message_received = nw0.wait_for_message_from(address, wait_for_s=5)
    nw0.send_reply_to(address, message_received)
    reply = reply_queue.get()
    assert reply == message_received
Beispiel #6
0
def test_send_reply(support):
    address = nw0.core.address()
    reply_queue = queue.Queue()

    support.queue.put(("send_reply_to", [address, reply_queue]))
    message_received = nw0.wait_for_message_from(address, wait_for_s=5)
    nw0.send_reply_to(address, message_received)
    reply = reply_queue.get()
    assert reply == message_received
def play_second(choose_move):
    moves = []
    # advertise
    my_address = nw0.advertise("RPS")
    # comm 1a
    # recv their hash
    their_hash = nw0.wait_for_message_from(my_address)

    # we don't know their move yet!
    my_move = decide_move(choose_move, their_move=None)

    my_salt = make_salt()
    my_hash = make_hash(my_move, my_salt)

    # comm 1b
    # reply with hash
    nw0.send_reply_to(my_address, my_hash)
    print('I send a sealed {}'.format(my_move))

    # comm 2a
    # receive their move + salt
    their_move_char, their_salt = nw0.wait_for_message_from(my_address)
    their_move = RPS(their_move_char)

    check_hash(their_move, their_salt, their_hash)

    # now we know their move, let's choose again!
    my_move = decide_move(choose_move, their_move=their_move)

    # comm 2b
    # reply with my move + salt
    nw0.send_reply_to(my_address, (my_move.char, my_salt))

    # my_move = RPS(my_move.char)
    moves.append(their_move)
    moves.append(my_move)

    print('They play', their_move)
    print('I play', my_move)
    return decide_winner(moves)
Beispiel #8
0
def wait_for_ip(address):
    print("waiting for ip")
    content = nw0.wait_for_message_from(address)
    pat = re.compile(".*\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
    test = pat.match(content)
    if not test:
        nw0.send_reply_to(address, "please input ip address")
        print("please input ip address")
        wait_for_ip(address)
    else:
        print("connected!")
        nw0.send_reply_to(address, "connected!")
        return content
Beispiel #9
0
def network_manager():
    address = nw0.advertise("GeneticAlgorithmsPathFindingGUIConsole")
    while True:
        message = nw0.wait_for_message_from(address, autoreply=True)
        genvar.set(message["generation"])
        itervar.set(message["iteration"])
        bdlgvar.set(message["bestlastgen"] + " (" + message["bestlastgenper"] +
                    "% left)")
        bdtgvar.set(message["bestthisgen"] + " (" + message["bestthisgenper"] +
                    "% left)")
        dmvar.set(message["dnamutcount"])
        deadvar.set(message["dead"] + " (" + message["deadper"] +
                    "% of population)")
        pvar.set(str(message["paused"]))
        if stop:
            break
def play_second(choose_move):
    moves = []
    # advertise
    my_address = nw0.advertise("RPS")
    # receive their move
    their_move = RPS(
        nw0.wait_for_message_from(my_address)
    )
    # reply with my move
    if isinstance(choose_move, type('')):
        my_move = RPS(choose_move)
    else:
        my_move = choose_move(their_move)
    nw0.send_reply_to(my_address, my_move.char)

    my_move = RPS(my_move.char)
    moves.append(their_move)
    moves.append(my_move)

    print('I play', my_move)
    print('They play', their_move)
    return decide_winner(moves)
Beispiel #11
0
        if len(line) > 4:
            new_q = Question(line[0], line[1:5], line[5])
            questions.append(new_q)

nwz.send_news_to(quiz_server, "Information", "Quiz Starting")

while len(questions) > 0:
    current_q = random.choice(questions)
    sleep(1)
    nwz.send_news_to(quiz_server, "Question", current_q.question)
    sleep(2)
    nwz.send_news_to(quiz_server, "Answers", current_q.answers)
    answered = 0
    while answered < len(players):
        for p in players:
            message = nwz.wait_for_message_from(p.connection, wait_for_s=0)
            if message is not None:
                answer = message[1]
                player = players[message[0]]
                if int(answer) == int(current_q.correct):
                    player.score += 1
                    nwz.send_reply_to(player.connection, "Correct! Your score is: " + str(player.score))
                else:
                    nwz.send_reply_to(player.connection, "Incorrect! Your score is: " + str(player.score))
                answered += 1
                message = None
        else:
            sleep(1)
    questions.remove(current_q)

nwz.send_news_to(quiz_server, "Information", "Quiz Finished")
Beispiel #12
0
import os, sys
import tempfile
import networkzero as nw0

address = nw0.advertise("gallery")
print("Gallery:", address)
while True:
    filename, data = nw0.wait_for_message_from(address, autoreply=True)
    bytes = nw0.string_to_bytes(data)
    
    temp_filepath = os.path.join(tempfile.gettempdir(), filename)
    with open(temp_filepath, "wb") as f:
        f.write(bytes)
    print("Wrote", temp_filepath)
import networkzero as nwz
from time import sleep

quiz_server = nwz.discover("Quiz")
address = nwz.address()
connection = nwz.advertise(address)
reply = nwz.send_message_to(quiz_server, address)
print(reply)
quiz_starting = False
while not quiz_starting:
    reply = nwz.wait_for_message_from(quiz_server,
                                      wait_for_s=0,
                                      autoreply=True)
    if reply is not None:
        print(reply)
    else:
        reply = nwz.wait_for_message_from(connection,
                                          wait_for_s=0,
                                          autoreply=True)
        if reply is not None:
            print(reply)
            if reply == "Quiz Starting":
                quiz_starting = True
        sleep(1)
print("Quiz loop starting")
quiz_over = False
while not quiz_over:
    reply = nwz.wait_for_message_from(connection, wait_for_s=0, autoreply=True)
    if reply is not None:
        #print(reply)
        if reply == "Next Question":
Beispiel #14
0
from quiz_player import Player
from Questions import Question
from time import time, sleep
import random

players = []
MAX_PLAYERS = 1

# Open the quiz server and bind it to a port - creating a socket
quiz_server = nwz.advertise('Quiz')
player_ID = 0

# Search for messages from participants until roster is full
while len(players) < MAX_PLAYERS:
    # Poll the server checking for rquests from participants
    message = nwz.wait_for_message_from(quiz_server, wait_for_s=0)
    # If a message has been recieved
    if message is not None:
        # Capture the address for the connection to the quiz client
        address = message
        print(address)
        conn = nwz.discover(address)
        players.append(Player(player_ID, address, conn))
        player_ID += 1
        nwz.send_reply_to(quiz_server, "Player acknowledged")
        reply = nwz.send_message_to(conn, "Welcome to the quiz")
        message = None
    else:
        sleep(1)
        if len(players) > 0:
            reply = nwz.send_message_to(
Beispiel #15
0
    '-' : operator.sub,
    '*' : multiply_the_Things
}

def questionator3000():
    n1 = random.randint(1, MAX_QUESTNUM)
    n2 = random.randint(1, MAX_QUESTNUM)
    o, op = random.choice(list(operations.items()))
    return "{} {} {}".format(n1,o,n2), str(op(n1,n2))


num_rounds = 0
score = 0

while True:
    greeting = nw0.wait_for_message_from(a)
    print("-> {}".format(greeting))

    question, expected_answer = questionator3000()

    reply1 = "Round #{}:\nQuestion: {}".format(num_rounds, question)
    nw0.send_reply_to(a, reply1)
    print("<- " + reply1)

    answer = nw0.wait_for_message_from(a)
    print("-> {}".format(answer))


    if answer == expected_answer:
        outcome = "correct!"
        score += 1
Beispiel #16
0
import networkzero as nw0

#
# If the hub is already running in another process, drop out
#
hub = nw0.discover("chat-hub", 3)
if hub is not None:
    raise SystemExit("Hub is already running on %s" % hub)

hub = nw0.advertise("chat-hub")
print("Hub on", hub)
updates = nw0.advertise("chat-updates")
print("Updates on", updates)
while True:
    action, params = nw0.wait_for_message_from(hub, autoreply=True)
    print("Action: %s, Params: %s" % (action, params))
    nw0.send_news_to(updates, action, params)
Beispiel #17
0
import networkzero as nw0

name = "A"

nw0.advertise("cluster/%s" % name)
master = nw0.discover("cluster/master")

while True:
    command = nw0.wait_for_message_from(master, autoreply=True)

    #
    # ... something goes wrong
    #
    raise RuntimeError
Beispiel #18
0
def test_wait_for_message_with_autoreply(support):
    address = nw0.core.address()
    reply_queue = queue.Queue()
    support.queue.put(("wait_for_message_from_with_autoreply", [address, reply_queue]))
    nw0.wait_for_message_from(address, autoreply=True)
    assert reply_queue.get() == nw0.messenger.EMPTY
Beispiel #19
0
else:
    first_word = ''

N_SECONDS_WAIT_FOR_NEIGHBOURS = 5
#
# Wait 30 seconds to discover all neighbours
#
print("Waiting %d seconds for neighbours to show up..." % N_SECONDS_WAIT_FOR_NEIGHBOURS)
time.sleep(N_SECONDS_WAIT_FOR_NEIGHBOURS)

print("Looking for neighbours")
addresses = [address for (name, address) in nw0.discover_group("halifax", exclude=[my_name])]
print(addresses)

while True:
    
    if first_word:
        word = first_word
        first_word = None
    else:
        print("Waiting for next word...")
        word = nw0.wait_for_message_from(my_address, autoreply=True)

    print("Got word", word)
    candidate_words = words[word[-1]]
    random.shuffle(candidate_words)
    next_word = candidate_words.pop()
    
    print("Sending word", next_word)
    nw0.send_message_to(random.choice(addresses), next_word)
Beispiel #20
0
# for the reader!
#
with open("words.txt") as f:
    words = f.read().split()

#
# Advertise service as 'anagram'
#
address = nw0.advertise("anagram")

while True:
    print("Waiting for a word...")
    #
    # Receive an anagram for which we have to find a match
    #
    anagram = nw0.wait_for_message_from(address).lower().strip()
    print("Looking for %s" % anagram)
    
    #
    # To compare two words we'll sort each and compare
    # the result. We need only sort the word we're searching
    # for once.
    #
    letters = "".join(sorted(anagram))
    
    #
    # Compare our incoming anagram, sorted, against each word
    # in turn, sorted. If we get a match, send the matching 
    # word and stop searching
    #
    for word in words:
Beispiel #21
0
def test_wait_for_message_with_timeout():
    address = nw0.core.address()
    message = nw0.wait_for_message_from(address, wait_for_s=0.1)
    assert message is None
Beispiel #22
0
import os, sys

import networkzero as nw0

if __name__ == '__main__':
    people = []

    chattery = nw0.advertise("chattery")

    while True:
        message = nw0.wait_for_message_from(chattery)
        action, params = nw0.action_and_params(message)
        action = action.upper()
        if action == "JOIN":
            name = params[0]
            code = "-".join(name.lower().split())
            people.append("chattery/%s" % code)

        elif action == "LEAVE":
        elif action == "SAY":
        else:
            print("Unknown command: %s" % action)
Beispiel #23
0
address = networkzero.advertise("foo")

STORE = {}


def my_func(input_data):
    try:
        command = json.loads(input_data)
        if command["cmd"] == "SET":
            STORE[command["key"]] = command["data"]
            response = {"status": "ok"}
        elif command["cmd"] == "GET":
            response = {
                "status": "ok",
                "info": STORE[command["key"]]
            }
        else:
            raise NotImplementedError(command)
    except:
        response = {
            "status": "error",
            "info": traceback.format_exc()
        }
    return json.dumps(response)


while True:
    input_data = networkzero.wait_for_message_from(address)
    print(input_data)
    networkzero.send_reply_to(address, my_func(input_data))
Beispiel #24
0
import os, sys
import tempfile
import networkzero as nw0

address = nw0.advertise("gallery")
while True:
    filename, data = nw0.wait_for_message_from(address, autoreply=True)
    bytes = nw0.string_to_bytes(data)
    
    temp_filepath = os.path.join(tempfile.gettempdir(), filename)
    with open(temp_filepath, "wb") as f:
        f.write(data)
    print("Wrote", temp_filepath)
Beispiel #25
0
import networkzero as nw0

address = nw0.advertise("reverso")
while True:
    message = nw0.wait_for_message_from(address)
    nw0.send_reply_to(address, message[::-1])
Beispiel #26
0
#
# Wait 30 seconds to discover all neighbours
#
print("Waiting %d seconds for neighbours to show up..." %
      N_SECONDS_WAIT_FOR_NEIGHBOURS)
time.sleep(N_SECONDS_WAIT_FOR_NEIGHBOURS)

print("Looking for neighbours")
addresses = [
    address
    for (name, address) in nw0.discover_group("halifax", exclude=[my_name])
]
print(addresses)

while True:

    if first_word:
        word = first_word
        first_word = None
    else:
        print("Waiting for next word...")
        word = nw0.wait_for_message_from(my_address, autoreply=True)

    print("Got word", word)
    candidate_words = words[word[-1]]
    random.shuffle(candidate_words)
    next_word = candidate_words.pop()

    print("Sending word", next_word)
    nw0.send_message_to(random.choice(addresses), next_word)
Beispiel #27
0
import networkzero as nwz

question = "What colour is the sky?|Red|Purple|Blue|Yellow"
answer = "Blue"
quiz_server = nwz.advertise('Quiz')
while True:
    nwz.wait_for_message_from(quiz_server)
    reply = nwz.send_message_to(quiz_server, question)
    print("Answer was... " + reply)
    if answer == reply:
        correct = "Correct"
    else:
        correct = "Wrong Answer"
    nwz.send_message_to(quiz_server, correct)
Beispiel #28
0
def test_wait_for_message_with_timeout():
    address = nw0.core.address()
    message = nw0.wait_for_message_from(address, wait_for_s=0.1)
    assert message is None
import networkzero as nw0

address = nw0.advertise("messenger2")

message = nw0.wait_for_message_from(address, autoreply=True)
print("Message received: ", message)
import networkzero as nwz
from time import sleep

quiz_server = nwz.discover("Quiz")
address = nwz.address()
connection = nwz.advertise("Quiz Participant :s" + address)
response = nwz.wait_for_message_from(connection, autoreply=True)
playerID = response
response = nwz.wait_for_message_from(connection)

response = ""
while response != "Done":
    news = nwz.wait_for_news_from(quiz_server)
    if news[0] == "Information":
        print("Quiz server says: " + news[1])
    elif news[0] == "Question":
        print("Incoming Question")
        print(news[1])
    elif news[0] == "Answers":
        answers = news[1]
        for i in range(len(answers)):
            print(str(i) + ". " + answers[i])
        print('Enter the number of your answer')
        my_answer = int(input(">"))
        reply = nwz.send_message_to(connection, [playerID, my_answer])
        print(reply)
    elif news[0] == playerID:
        print(news[1])
import networkzero as nw0

address = nw0.advertise("service")
message = nw0.wait_for_message_from(address)
print("Message received: ", message)
nw0.send_message_to(address, "Received: %s" % message)