Last active
August 29, 2015 13:58
-
-
Save aurynn/10023699 to your computer and use it in GitHub Desktop.
Simple JSON Server 1
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
from twisted.internet import protocol, reactor | |
from twisted.protocols.basic import LineReceiver | |
from twisted.internet.endpoints import TCP4ServerEndpoint | |
import json | |
class JsonEchoServer(LineReceiver): | |
""" | |
Implements the server-side mechanisms | |
""" | |
def connectionMade(self): | |
print "Connected!" | |
self.sendLine(json.dumps({"from":"server", "message": "connected"})) | |
def lineReceived(self, line): | |
"""Receives a line from our remote""" | |
print "Line!" | |
m = None | |
try: | |
m = json.loads(line) | |
except json.JSONDecodeError as e: | |
self.sendLine(json.dumps( | |
{ | |
"from": "server", | |
"message": "json parse error {error}".format(e)} | |
)) | |
print "received non-json-decodable string" | |
return | |
self.sendLine(json.dumps( | |
{ "from": "EchoServer", "message": "%s said '%s'" % ( m["from"], m["message"] ) } | |
) | |
) | |
class EchoFactory(protocol.Factory): | |
def buildProtocol(self, addr): | |
e = JsonEchoServer() | |
return e | |
endpoint = TCP4ServerEndpoint(reactor, 1234) | |
endpoint.listen(EchoFactory()) | |
reactor.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment