Skip to content

Instantly share code, notes, and snippets.

@aurynn
Last active November 2, 2017 17:51
Show Gist options
  • Save aurynn/10023139 to your computer and use it in GitHub Desktop.
Save aurynn/10023139 to your computer and use it in GitHub Desktop.
Simple JSON client 2
from twisted.internet.protocol import Factory
from twisted.internet.endpoints import TCP4ClientEndpoint
from twisted.internet import reactor
from twisted.protocols.basic import LineReceiver
import json
your_name = "aurynn"
class JsonProtocol(LineReceiver):
def lineReceived(self, msg):
try:
msg = json.loads(msg)
except json.JSONDecoderError:
print "Received a non-JSON message: %s" % msg
print "<{from}> {message}".format(**msg)
def sendMessage(self, msg):
self.sendLine( json.dumps( {
"to": "EchoTest",
"from": your_name,
"message": msg
} ) )
class EchoClientFactory(Factory):
def buildProtocol(self, addr):
return JsonProtocol()
endpoint = TCP4ClientEndpoint(reactor, server_ip, 1234 )
deferred = endpoint.connect(EchoClientFactory())
reactor.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment