Skip to content

Instantly share code, notes, and snippets.

@ysimonson
Last active August 14, 2017 02:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ysimonson/cbddab30e061d48e51365af25d484d00 to your computer and use it in GitHub Desktop.
Save ysimonson/cbddab30e061d48e51365af25d484d00 to your computer and use it in GitHub Desktop.
import socket
import re
PORT = 1075
LINE_VALIDATOR = re.compile(r"(0|1) (0|1) (0|1) (0|1) (0|1)")
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("0.0.0.0", PORT))
while True:
data, addr = s.recvfrom(1024)
print("Received data from %s:%s" % addr)
lines = data.decode("ascii").split("\n")
assert len(lines) == 8, "Expected there to be 8 lines separated by linefeeds (0x0a)"
assert lines[0] == "0", "Expected version number to be 0"
assert lines[1] == "5", "Expected width to be 5"
assert lines[2] == "5", "Expected height to be 5"
for i, line in enumerate(lines[3:]):
assert LINE_VALIDATOR.match(line), "Line %s: Invalid pattern, must be 5 space-separated characters of '1' or '0'" % (i + 4)
print("Message is valid: %s" % data)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment