Skip to content

Instantly share code, notes, and snippets.

@smartkiwi
Last active December 16, 2015 15:58
Show Gist options
  • Save smartkiwi/5459315 to your computer and use it in GitHub Desktop.
Save smartkiwi/5459315 to your computer and use it in GitHub Desktop.
posa pa 3
"""
POSA PA 3 program
Echo Server
built and tested using python 2.7.2 and Twisted 12.0.0
"""
import sys
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
from twisted.python import log
class EchoServerHandler(Protocol):
"""Event Handler - Reactor passes control to it after receiving data event"""
def connectionMade(self):
log.msg("Client connection")
self.transport.write("Hi there. I'm an Echo Server. You can stop me by sending quit message\n")
def dataReceived(self, data):
"""
Similar to Wrapper Facade - called by Reactor after receiving data from socket stream
"""
log.msg("data received %s bytes: %s" % (len(data),data))
self.transport.write(data)
if "quit" in data:
self.transport.write("Bye bye\n")
self.transport.loseConnection()
reactor.callFromThread(reactor.stop)
def connectionLost(self, reason):
log.msg("client disconnected")
class EchoServerFactory(Factory):
"""Acceptor - handles connection event - takes care about instantiating Event Handler object"""
def buildProtocol(self, addr):
log.msg("EchoServerFactory %s" % addr)
return EchoServerHandler()
def main():
"""
Main program
Starts Echo Server to listen on 5555 port
You can test it with command:
telnet localhost 5555
"""
log.startLogging(sys.stdout)
"""twisted.internet.reactor module takes care about running server - configures TCP listener and runs the event loop
thus it implements Reactor pattern - handles service requests that are delivered concurrently to an application by one or more clients
Also the reactor provides basic interfaces to a number of services, including network communications, threading, and event dispatching - thus it implements Wrapper Facade pattern
"""
reactor.listenTCP(5555, EchoServerFactory())
reactor.run()
if __name__=='__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment