john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

server chat example

# 2013-04-29 johnpfeiffer , run using python c:\Python27\Scripts\twistd.py  -y c:\Users\User\Desktop\example.py
# the expected client in this example is telnet, e.g. telnet localhost 8000

from twisted.protocols.basic import LineReceiver

class MyChat( LineReceiver ):
    def connectionMade( self ):
        print "Someone joined the chat"
        self.factory.clients.append( self )

    def connectionLost( self ):
        print "Someone left the chat"
        self.factory.clients.remove( self )

    def lineReceived(self, line):
        print "received", repr(line)    # server log
        for c in self.factory.clients:
            c.transport.write( line + '\n' )


from twisted.application import service
from twisted.application import internet
from twisted.internet.protocol import ServerFactory

factory = ServerFactory()
factory.protocol = MyChat
factory.clients = list()

application = service.Application( "chatserver" )
internet.TCPServer( 8000, factory ).setServiceParent( application )

  • « graph
  • server chat improved example »

Published

Apr 29, 2013

Category

python-twisted

~88 words

Tags

  • chat 19
  • example 36
  • python 180
  • server 66
  • twisted 20