Skip to content

Instantly share code, notes, and snippets.

@aurynn
Created April 9, 2014 15:14
Show Gist options
  • Save aurynn/10281816 to your computer and use it in GitHub Desktop.
Save aurynn/10281816 to your computer and use it in GitHub Desktop.
echo client/server
# Shamelessly stolen from the Twisted site
from twisted.internet import protocol, reactor, defer
from twisted.protocols.basic import LineReceiver
from twisted.internet.endpoints import TCP4ServerEndpoint
import json
class JsonEchoServer(LineReceiver):
"""
Implements the server-side mechanisms
"""
def __init__(self, *args):
# LineReceiver.__init__(self, *args)
self.acks = {}
self.msgid = 0
def connectionMade(self):
print "Connected!"
msg = {"from": "server",
"message": "connected",
"id": self.msgid}
self.sendLine(json.dumps(msg))
self.acks[self.msgid] = msg
self.msgid += 1
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),
"addr": self.addr
}
))
print "received non-json-decodable string"
return
self.factory.relay(m)
def send(self, msg):
self.sendLine(json.dumps(msg))
class JsonClientProto(JsonEchoServer):
def connectionMade(self):
print "connected to remote"
class EchoFactory(protocol.Factory):
def __init__(self, *args):
self.peers = []
def buildProtocol(self, addr):
e = JsonEchoServer()
e.addr = addr
e.factory = self
self.peers.append(
{"addr": addr,
"proto": e}
)
return e
def relay(self, msg, origin):
for peer in peers:
if peer["addr"] == origin:
continue
peer["proto"].send(msg)
echofactory = EchoFactory()
class EchoClientFactory(protocol.Factory):
def buildProtocol(self, addr):
p = JsonClientProto()
p.factory = echofactory
peer = {
"peer": addr,
"proto": p}
# This does not even BEGIN to handle disconnects
echofactory.peers.append(peer)
peers= []
def started(port):
# called by the server endpoint when it's able to listen
f = EchoClientFactory()
for peer in peers:
ep = TCP4ClientEndpoint(reactor, peer, 1235)
ep.connect(f)
endpoint = TCP4ServerEndpoint(reactor, 1235)
df = endpoint.listen()
df.addCallback(started)
reactor.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment