def play_first(choose_move): moves = [] # discover my_address = nw0.discover('RPS') # 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) print(my_salt, my_hash) # comm 1 # send my hash # recv their hash back their_hash = nw0.send_message_to(my_address, my_hash) print('I send a sealed {}'.format(my_move)) # comm 2 # send my move + salt # recv their move + salt back their_move_char, their_salt = nw0.send_message_to( my_address, (my_move.char, my_salt)) their_move = RPS(their_move_char) check_hash(their_move, their_salt, their_hash) moves.append(my_move) moves.append(their_move) print('I play', my_move) print('They play', their_move) return decide_winner(moves)
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 __init__(self): self.log_queue = collections.deque(maxlen=self.height // self.log_font_h) self.channels = {} for name in self.channel_names: address = nw0.discover("piwars/%s" % name, wait_for_s=3) if address: self.channels[name] = address else: print("WARNING: No channel found for", name) self.channel_locks = {} for name in self.channel_names: self.channel_locks[name] = threading.Lock() self.channel_values = {}
def play_first(choose_move): moves = [] # discover my_address = nw0.discover('RPS') if isinstance(choose_move, six.string_types): my_move = RPS(choose_move) else: # we don't know their move yet! my_move = choose_move(their_move=None) # send my move, and get their move back their_move = RPS( nw0.send_message_to(my_address, my_move.char) ) moves.append(my_move) moves.append(their_move) print('I play', my_move) print('They play', their_move) return decide_winner(moves)
def __init__(self, name, parent=None): super(Chatter, self).__init__(parent) self.name = name self.text_panel = QtWidgets.QTextEdit() self.text_panel.setReadOnly(True) self.input = QtWidgets.QLineEdit() layout = QtWidgets.QVBoxLayout() layout.addWidget(self.text_panel, 3) layout.addWidget(self.input, 1) self.setLayout(layout) self.setWindowTitle("Chatter") self.input.editingFinished.connect(self.input_changed) self.input.setFocus() self.chattery = nw0.discover("chattery/news") self.responder = FeedbackReader(self.chattery) self.responder.message_received.connect(self.handle_response) self.responder.start()
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)
def test_discover_before_advertise(beacon, support): service1 = uuid.uuid4().hex support.queue.put(("discover_before_advertise", [service1])) address1 = nw0.discover(service1, wait_for_s=5) assert address1 is not None
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]) player_ID += 1 else: sleep(1) if len(players) > 0: nwz.send_news_to(quiz_server, "Information", "Waiting for... " + str(MAX_PLAYERS -len(players)) + " players") sleep (5) questions = [] with open("questions.csv", 'r') as file: for line in file.readlines(): line = line.split(',')
import networkzero as nw0 print("Looking for chat updates channel") updates = nw0.discover("chat-updates") if not updates: print("Unable to find chat updates channel after 60s") raise SystemExit print("Chat updates found at", updates) while True: action, message = nw0.wait_for_news_from(updates) if action is None: break elif action == "JOIN": print("%s has joined" % message) elif action == "LEAVE": print("%s has left" % message) elif action == "SPEAK": [person, words] = message print("%s says: %s" % (person, words)) else: print("!! Unexpected message: %s" % message)
def test_discover(beacon): service = uuid.uuid4().hex address = nw0.advertise(service) assert address == nw0.discover(service)
def test_discover_before_advertise(beacon, support): service1 = uuid.uuid4().hex support.queue.put(("discover_before_advertise", [service1])) address1 = nw0.discover(service1, wait_for_s=5) assert address1 is not None
import networkzero as nw0 address = nw0.discover("news2") while True: topic, humidity = nw0.wait_for_news_from(address, "humidity") print("Humidity is:", humidity)
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( players[0].connection, "Waiting for... " + str(len(players) - MAX_PLAYERS)) questions = [] with open("../questions.csv", 'r') as file: for line in file.readlines():
import networkzero as nw0 news = nw0.discover("blink_news") while True: topic, message = nw0.wait_for_news_from(news, "BLINK") print(message)
import networkzero as nw0 try: # Python 2.7 compat input = raw_input except NameError: pass reverso = nw0.discover("reverso") while True: word = input("Enter word: ") reversed_word = nw0.send_message_to(reverso, word) print("Reversed:", reversed_word)
import ast import itertools import sys import time import networkzero as nw0 t = 'server_team_4' a = nw0.discover(t) def get_ans(question, n): return input("What's the answer? ") if len(sys.argv) > 1 and sys.argv[1] == 'hard': from t1000 import get_ans for round in itertools.count(): # print('ROUND {}'.format(round)) question = nw0.send_message_to(a, "-> I'm ready!") print('<- {}'.format(question)) ans = get_ans(question, round) print("-> {}".format(ans)) n = nw0.send_message_to(a, ans) print('<- {}'.format(n)) print()
import networkzero as nw0 address = nw0.discover("reverso") while True: word = input("Enter word: ") reversed_word = nw0.send_message(address, word) print("Reversed:", reversed_word)
import os, sys import networkzero as nw0 try: input = raw_input except NameError: pass gallery = nw0.discover("gallery") filepath = input("Filename: ") filename = os.path.basename(filepath) with open(filepath, "rb") as f: data = f.read() nw0.send_message_to(gallery, (filename, nw0.bytes_to_string(data)))
import time import networkzero as nw0 service = nw0.discover("poller1") time.sleep(3) reply = nw0.send_message_to(service, "This is a message") print("Reply: ", reply)
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
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)
import networkzero as nw0 updates = nw0.discover("chat-updates") while True: action, message = nw0.wait_for_notification(updates) print(action, message) if action == "JOIN": print("%s has joined" % message) elif action == "LEAVE": print("%s has left" % message) elif action == "SPEAK": [person, words] = message print("%s says: %s" % (person, words)) else: print("!! Unexpected message: %s" % message)
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 networkzero as nw0 service = nw0.discover("messenger2") nw0.send_message_to(service, "This is a command")
def test_discover_exists_with_timeout(beacon): service = uuid.uuid4().hex address = nw0.advertise(service) assert address == nw0.discover(service, wait_for_s=2)
if int(sys.argv[10]) == 1: print("Welcome to Genetic Algorithms: Path Finding") print("Click and hold anywhere to draw a barrier.") print("Use [BACKSPACE] to toggle the eraser.") print("Use [SPACE] to paused and resume.") if Constants.DNA_LENGTH * 4 < length: if len(sys.argv) > 10: if int(sys.argv[10]) == 1: print("The creature's possible traveling distance is shorter than the distance from start to end. Aborting.") running = False if len(sys.argv) > 10: if int(sys.argv[10]) == 1: print("Press [SPACE] to start.") print("When done, use CTRL + C or click on the Genetic Algorithms: Path Finding's X button.") console = nw0.discover("GeneticAlgorithmsPathFindingGUIConsole") counter = 0 screen.fill((255, 255, 255)) for entity in sprites: screen.blit(entity.surf, entity.rect) pygame.display.flip() while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == keys.KEYDOWN: if event.key == keys.K_SPACE: do = not do if event.key == keys.K_BACKSPACE:
import networkzero as nw0 myservice = nw0.discover("myservice5") print("myservice is at", myservice)
def test_discover(beacon): service = uuid.uuid4().hex address = nw0.advertise(service) assert address == nw0.discover(service)
import networkzero as nw0 name = "cluster/master" address = nw0.advertise(name) # # On the cluster master # nodes = set(nw0.discover_group("cluster", exclude=name)) old_nodes = nodes print("Nodes:", ", ".join(nodes)) # # Send a command to A .... which will unaccountably fail # node_a = nw0.discover("cluster/A") nw0.send_message_to(node_a, "STOP") # # Wait a few seconds for node C to wake up # time.sleep(5) # # On the cluster master # nodes = set(nw0.discover_group("cluster")) for name, address in old_nodes - nodes: print("%s has left the cluster" % name) for name, address in nodes - old_nodes: print("%s has joined the cluster" % name)
from __future__ import print_function import networkzero as nw0 try: # Python 2.7 compat input = raw_input except NameError: pass service = nw0.discover("anagram") while True: anagram = input("Enter anagram: ") word = nw0.send_message_to(service, anagram) if word: print(word) else: print("Nothing found")
import networkzero import time import json def get_key(key): return networkzero.send_message_to(server, json.dumps({ "cmd": "GET", "key": key })) def set_key(key, value): return networkzero.send_message_to(server, json.dumps({ "cmd": "SET", "key": key, "data": value })) server = networkzero.discover("foo") print(set_key("foo", "bar")) print(get_key("foo"))
import networkzero as nw0 updates = nw0.discover("board-updates") while True: topic, board = nw0.wait_for_notification(updates, "status") # # Show the latest state of the board # print() print() for row in "ABC": for column in "123": value = board.get("%s%s" % (row, column), "-") print(value, sep="", end="") print()
import networkzero as nw0 address = nw0.discover("board") player = input("Which player? ") while True: move = input("Move: ") nw0.send_command(address, "MOVE '%s' '%s'" % (player, move))
def test_discover_not_exists_with_timeout(beacon): service = uuid.uuid1().hex address = nw0.advertise(service) assert None is nw0.discover(uuid.uuid1().hex, wait_for_s=2)