Last active
July 6, 2017 18:06
-
-
Save johnpena/c2710a7409e6f744d3786db2534cedd0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import requests | |
import json | |
import random | |
from http.server import HTTPServer, BaseHTTPRequestHandler | |
class MessageHandler(BaseHTTPRequestHandler): | |
def __init__(self): | |
BaseHTTPRequestHandler.__init__() | |
self.current_timestamp = random.randint(1000, 5000) | |
def do_GET(self): | |
self.current_timestamp += random.randint(1, 100) | |
message = "ping" if self.current_timestamp % 2 == 0 else "pong" | |
return json.dumps({"message": message, "timestamp": self.current_timestamp}) | |
def run(): | |
"""example handler""" | |
for port in range(8000, 8081): | |
httpd = HTTPServer(("", port), MessageHandler) | |
httpd.serve_forever() | |
class Message: | |
def __init__(self, timestamp, message): | |
self.timestamp = timestamp # assumed to be an int | |
self.message = message | |
class Stream: | |
def __init__(self, hostname): | |
self.hostname = hostname | |
def get(): | |
data = requests.get(hostname).content | |
parsed = json.loads(data) | |
return Message(parsed['timestamp'], parsed['message']) | |
def send(message): | |
print(f"{message.timestamp} - {message.message}") | |
def main(): | |
port_range = range(8000, 8081) | |
streams = [Stream(f"localhost:{port}") for port in port_range] | |
messages = [stream.get() for stream in streams] | |
while True: | |
# re-poll from the stream that sent the most recently timestamped message. | |
# on the first loop, this will be skipped. | |
for i, message in enumerate(messages): | |
if message is None: | |
messages[i] = streams[i].get() | |
most_recent_timestamp = sys.MAXINT | |
message_index = None | |
for i, message in enumerate(results): | |
if message.timestamp < most_recent_timestamp: | |
most_recent_timestamp = message.timestamp | |
message_index = i | |
send(message) | |
messages[message_index] = None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment