Created
September 27, 2014 19:14
-
-
Save zopieux/a6957a80b63f9906afa0 to your computer and use it in GitHub Desktop.
Quizz Fever networking
This file contains 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
def messageToBytes(type, body=None): | |
data = {'type': type} | |
if body is not None: | |
data['body'] = body | |
try: | |
return json.dumps(data).encode('ascii') + b"\n" | |
except ValueError: | |
raise ValueError("message could not be JSON-encoded") | |
except UnicodeEncodeError: | |
raise UnicodeEncodeError("JSON could not be converted to bytes") | |
def bytesToMessage(msg): | |
try: | |
data = json.loads(msg.decode('ascii')) | |
return data['type'], data.get('body', None) | |
except UnicodeDecodeError: | |
raise UnicodeEncodeError("Incoming message is not ASCII-encoded") | |
except ValueError: | |
raise ValueError("Incoming message is not valid JSON") | |
except KeyError: | |
raise ValueError("Incoming message is malformed") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment