Skip to content

Instantly share code, notes, and snippets.

@bmannix
Forked from aurynn/gist:10121896
Last active August 29, 2015 13:58
Show Gist options
  • Select an option

  • Save bmannix/10301435 to your computer and use it in GitHub Desktop.

Select an option

Save bmannix/10301435 to your computer and use it in GitHub Desktop.
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 = "bmannix"
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, "10.99.132.198", 1234 )
# 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