def test_discover_all(beacon): service1 = uuid.uuid4().hex address1 = nw0.advertise(service1) service2 = uuid.uuid4().hex address2 = nw0.advertise(service2) services = dict(nw0.discover_all()) assert services == {service1:address1, service2:address2}
def test_discover_all(beacon): service1 = uuid.uuid4().hex address1 = nw0.advertise(service1) service2 = uuid.uuid4().hex address2 = nw0.advertise(service2) services = dict(nw0.discover_all()) assert services == {service1: address1, service2: address2}
def test_discover_group(beacon): group = uuid.uuid4().hex service1 = "%s/%s" % (group, uuid.uuid4().hex) service2 = "%s/%s" % (group, uuid.uuid4().hex) service3 = "%s/%s" % (uuid.uuid4().hex, uuid.uuid4().hex) address1 = nw0.advertise(service1) address2 = nw0.advertise(service2) address3 = nw0.advertise(service3) discovered_group = nw0.discover_group(group) assert set(discovered_group) == set([(service1, address1), (service2, address2)])
def test_discover_group_with_different_separator(beacon): group = uuid.uuid4().hex service1 = "%s:%s" % (group, uuid.uuid4().hex) service2 = "%s:%s" % (group, uuid.uuid4().hex) service3 = "%s:%s" % (uuid.uuid4().hex, uuid.uuid4().hex) address1 = nw0.advertise(service1) address2 = nw0.advertise(service2) address3 = nw0.advertise(service3) discovered_group = nw0.discover_group(group, separator=":") assert set(discovered_group) == set([(service1, address1), (service2, address2)])
def _test_unadvertise_with_timeout(): """Adverts are unadvertised when a process exits (via atexit.register). However, if the local beacon has already stopped, any attempt to send it a message will block. """ # # Start a beacon on a random port and register an arbitrary # service. We need to know neither the port nor the service; # all we do is check unadvertising will succeed. # nw0.discovery._start_beacon(port=random.choice(nw0.config.DYNAMIC_PORTS)) nw0.advertise(uuid.uuid4().hex) nw0.discovery._stop_beacon()
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
def test_unadvertise(beacon): ttl_s = 2 service = uuid.uuid4().hex address = nw0.advertise(service, ttl_s=ttl_s) assert [service, address] in nw0.discover_all() nw0.discovery._unadvertise(service) time.sleep(1 + ttl_s) assert [service, address] not in nw0.discover_all()
def test_advertise_ttl(beacon): service = uuid.uuid4().hex ttl_s = 5 address = nw0.advertise(service, ttl_s=ttl_s) assert [service, address] in nw0.discover_all() # # Stop advert broadcast for long enough that any # stale ones will be expired # nw0.discovery._pause() try: time.sleep(1 + ttl_s) assert [service, address] not in nw0.discover_all() finally: nw0.discovery._resume()
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 main(n_threads=4, finish_at=1000): collector = nw0.advertise("collector") threads = [] for n in range(n_threads): threads.append(threading.Thread(target=do, args=(finish_at, 1 if n == 0 else None))) for thread in threads: thread.setDaemon(True) thread.start() collected = {} while True: name, number = nw0.wait_for_message(collector) collected.setdefault(name, set()).add(number) print(name, number) if number >= finish_at: break for name, numbers in collected.items(): print(name, "=>", len(numbers))
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)
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)
def do(finish_at, number=None): collector = nw0.discover("collector") group = "keep-going" name = "%s/%s" % (group, uuid.uuid4().hex) address = nw0.advertise(name) time.sleep(3) neighbours = [address for name, address in nw0.discover_group(group, exclude=[name])] while True: if number is not None: log("About to send %s-%s to collector", name, number) nw0.send_message(collector, (name, number)) if number < finish_at: log("About to send %s to %s", number+1, neighbours) nw0.send_message(neighbours, number + 1) # # Wait up to three seconds for a number and then give up # log("Waiting for message from %s", address) number = nw0.wait_for_message(address, wait_for_s=3) if number is None: break
def test_discover_exists_with_timeout(beacon): service = uuid.uuid4().hex address = nw0.advertise(service) assert address == nw0.discover(service, wait_for_s=2)
import networkzero as nw0 address = nw0.advertise("reverso") while True: message = nw0.wait_for_message_from(address) nw0.send_reply_to(address, message[::-1])
def test_advertise_full_address(beacon): service = uuid.uuid4().hex service_address = "192.168.1.1:1234" address = nw0.advertise(service, service_address) assert address == service_address assert [service, address] in nw0.discover_all()
import networkzero as nw0 address = "localhost:1234" nw0.advertise("myservice", address)
def __init__(self, name, queue, finish_event, *args, **kwargs): super(NewsThread, self).__init__(name=name, *args, **kwargs) self.news = nw0.advertise("piwars/%s" % as_code(name)) self.queue = queue self._finish_event = finish_event
def test_advertise_no_address(beacon): service = uuid.uuid4().hex address = nw0.advertise(service) assert is_valid_address(address) assert [service, address] in nw0.discover_all()
def support_test_discover_before_advertise(self, service): time.sleep(1) nw0.advertise(service)
import networkzero as nw0 address = nw0.advertise("myservice1") print("Service is at", address)
import json import traceback import networkzero 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)
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":
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 quiz_player import Player from Questions import Question from time import time, sleep import random players = [] player_addresses = [] MAX_PLAYERS = 2 # 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 requests from participants connections = nwz.discover_all() #print(connections) # If a message has been recieved if len(connections) > 0: for c in connections: # Capture the address for the connection to the quiz client if "Quiz Participant" in c[0] and c[1] not in player_addresses: print(connections) nwz.send_news_to(quiz_server, "Information", "Player acknowledged" + c[1]) conn = nwz.discover(c[0]) response = nwz.send_message_to(conn, player_ID) nwz.send_reply_to(conn) players.append(Player(player_ID, c[1], conn)) player_addresses.append(c[1])
import networkzero as nw0 alice = nw0.advertise("chat/alice")
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
def test_advertise_no_port(beacon): service = uuid.uuid4().hex address = nw0.advertise(service) assert is_valid_address(address, port_range=nw0.config.DYNAMIC_PORTS) assert [service, address] in nw0.discover_all()
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)
import networkzero as nw0 address = nw0.advertise("myservice")
import networkzero as nw0 address = nw0.advertise("messenger2") message = nw0.wait_for_message_from(address, autoreply=True) print("Message received: ", message)
def test_discover(beacon): service = uuid.uuid4().hex address = nw0.advertise(service) assert address == nw0.discover(service)
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)
def advertise(): name = f'{socket.gethostname()}-{str(uuid.uuid4())[:8]}' address = nw0.advertise(name) # hostname..uuid return address
import operator import sys import random import networkzero as nw0 if len(sys.argv) > 1 and sys.argv[1] == 'easy': MAX_QUESTNUM = 10 else: MAX_QUESTNUM = 100 t = 'server_team_4' a = nw0.advertise(t) def multiply_the_Things(y,x): a = 0 for i in range(x): a += y return a operations = { '+' : lambda x,y:x+y, '/' : lambda x,y:x//y, '-' : operator.sub, '*' : multiply_the_Things } def questionator3000(): n1 = random.randint(1, MAX_QUESTNUM)
import networkzero as nw0 nw0.advertise("myservice", 1234)
import sys import random import time import traceback import uuid import networkzero as nw0 words = {} with open("words.txt") as f: for word in f: words.setdefault(word[0], []).append(word.strip()) my_name = "halifax/" + uuid.uuid4().hex my_address = nw0.advertise(my_name) if len(sys.argv) == 2: first_word = sys.argv[1].lower().strip() 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
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)
import networkzero as nw0 bob = nw0.advertise("chat/bob")
import networkzero as nw0 nw0.advertise("myservice5")
import networkzero as nw0 notifications = nw0.advertise("board-updates") address = nw0.advertise("board") board = {} while True: command, params = nw0.wait_for_command(address) print("Command %s with params %s" % (command, params)) # # Depending on what the command is, update the board or do whatever # is needed. # if command == "MOVE": [player, move] = params board[move] = player elif command == "RESTART": board.clear() # # Send a notification to all subscribers that the board has changed # nw0.send_notification(notifications, "status", board)