Skip to content

Instantly share code, notes, and snippets.

@artizirk
Last active June 30, 2018 19:49
Show Gist options
  • Save artizirk/5532633 to your computer and use it in GitHub Desktop.
Save artizirk/5532633 to your computer and use it in GitHub Desktop.
twisted message broadcast kind of a thing needs msgpack
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import print_function
from twisted.python import log
from twisted.internet.protocol import Factory
from twisted.protocols.basic import NetstringReceiver
from twisted.internet import reactor
from uuid import uuid4 as get_uuid
import sys
class BrokerServer(NetstringReceiver):
def __init__(self, cons):
self.cons = cons #connections from facotry
self.uuid = str(get_uuid()) #this connection uuid
def connectionMade(self):
self.cons[self.uuid] = self
print("new client:", self.uuid[24:])
def connectionLost(self, reason):
print("client disconnect:", self.uuid[24:])
if self.uuid in self.cons:
del self.cons[self.uuid]
def stringReceived(self, line):
for uuid, conn in self.cons.iteritems():
if uuid != self.uuid: #don't send packet back to the originating clien
conn.sendString(line)
class BrokerFactory(Factory):
def __init__(self):
self.cons = {} # holds connections
def buildProtocol(self, addr):
return BrokerServer(self.cons)
log.startLogging(sys.stdout)
reactor.listenTCP(8123, BrokerFactory())
reactor.run()
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import print_function
from twisted.internet import reactor
from twisted.internet.protocol import ReconnectingClientFactory
from twisted.protocols.basic import NetstringReceiver
from twisted.python import log
import msgpack
import sys
print("run me twice ;)")
class BrokerClient(NetstringReceiver):
def connectionMade(self):
print("connected")
msg = msgpack.dumps({"type":"test", "Hello":"World"})
self.sendString(msg)
def connectionLost(self, reason):
print("connection lost")
def stringReceived(self, line):
print("recived:", msgpack.loads(line))
class BrokerFactory(ReconnectingClientFactory):
protocol = BrokerClient
if __name__ == '__main__':
log.startLogging(sys.stdout)
reactor.connectTCP("localhost", 8123, BrokerFactory())
reactor.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment