Last active
August 29, 2015 13:58
-
-
Save aurynn/10023253 to your computer and use it in GitHub Desktop.
Simple JSON client 3
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.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): | |
print "Sending a line?" | |
self.sendLine( json.dumps( { | |
"to": "EchoTest", | |
"from": your_name, | |
"message": msg | |
} ) ) | |
class EchoClientFactory(Factory): | |
def buildProtocol(self, addr): | |
return JsonProtocol() | |
def on_connect(protocol): | |
# Remember that a protocol proxies for one wire connection | |
protocol.sendMessage("hello remote server") | |
protocol.sendMessage("hello?") | |
endpoint = TCP4ClientEndpoint(reactor, "localhost", 1234 ) | |
deferred = endpoint.connect(EchoClientFactory()) | |
deferred.addCallback(on_connect) | |
reactor.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
10.99.132.198