Created
April 8, 2014 13:11
-
-
Save aurynn/10121896 to your computer and use it in GitHub Desktop.
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, connectProtocol | |
from twisted.internet import reactor, defer, stdio | |
from twisted.protocols.basic import LineReceiver | |
import json | |
your_name = "aurynn" | |
class NotConnectedError(BaseException): pass | |
class JsonProtocol(LineReceiver): | |
def __init__(self, *args): | |
# LineReceiver.__init__(self, *args) | |
self.msgs = {} | |
self.msgid = 0 | |
self.output = None | |
def lineReceived(self, msg): | |
try: | |
msg = json.loads(msg) | |
except json.JSONDecoderError: | |
print "Received a non-JSON message: %s" % msg | |
self.output.sendMessage(msg) | |
def sendMessage(self, msg): | |
print "woo" | |
msg = { | |
"to": "EchoTest", | |
"from": your_name, | |
"message": msg, | |
"id": self.msgid | |
} | |
self.sendLine( json.dumps( msg ) ) | |
df = defer.Deferred() | |
self.msgs[self.msgid] = {"msg": msg, "deferred": df } | |
self.msgid += 1 | |
return df | |
class StdioProtocol(LineReceiver): | |
from os import linesep as delimiter | |
def connectionMade(self): | |
self.connected = True | |
def __init__(self, wire): | |
self.chat = wire | |
wire.output = self | |
def lineReceived(self, line): | |
# print "Got line: %s" % line | |
try: | |
self.chat.sendMessage(line) | |
except NotConnectedError as e: | |
self.metaMessage(e) | |
def sendMessage(self, line): | |
if not self.connected: | |
raise NotConnectedError("Not connected") | |
self.sendLine(str("<{from}> {message}".format(**line) )) | |
def on_connect(protocol): | |
# Remember that a protocol proxies for one wire connection | |
df = protocol.sendMessage("hello remote server") | |
df.addCallback(acknowledge) | |
wire = JsonProtocol() | |
stdio_ = StdioProtocol(wire) | |
stdio.StandardIO(stdio_) | |
endpoint = TCP4ClientEndpoint(reactor, "localhost", 1235 ) | |
# deferred = endpoint.connect( EchoClientFactory() ) | |
deferred = connectProtocol(endpoint, wire) | |
deferred.addCallback(on_connect) | |
reactor.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment