Skip to content

Instantly share code, notes, and snippets.

@minmax
Last active August 29, 2015 14:26
Show Gist options
  • Save minmax/ecd91c752cdc9ff0281b to your computer and use it in GitHub Desktop.
Save minmax/ecd91c752cdc9ff0281b to your computer and use it in GitHub Desktop.
from twisted.internet.task import react
from twisted.internet.defer import Deferred
from twisted.internet.protocol import Factory, connectionDone
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.protocols.basic import LineReceiver
class ChatProtocol(LineReceiver):
def lineReceived(self, line):
self.factory.send_message(self, line)
def connectionMade(self):
self.factory.connect(self)
def connectionLost(self, reason=connectionDone):
self.factory.disconnect(self)
@property
def address(self):
return self.transport.getPeer()
class ChatFactory(Factory, object):
protocol = ChatProtocol
def __init__(self):
self.clients = []
def send_message(self, author, line):
for protocol in self.clients:
if protocol is not author:
addr = protocol.address
protocol.sendLine('{}:{}>>{}'.format(addr.host, addr.port, line))
def connect(self, protocol):
self.clients.append(protocol)
def disconnect(self, protocol):
self.clients.remove(protocol)
def main(reactor):
endpoint = TCP4ServerEndpoint(reactor, 51234)
endpoint.listen(ChatFactory())
return Deferred()
if __name__ == '__main__':
react(main)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment