Twisted server for multiple clients
Question: I want to write a server that can accept multiple clients in python (twisted).
I am already quite familiar with socket programming with the standard python
socket module but here comes the trouble.. I think twisted is really hard to
get into and i have read some tutorials about it. But a thing that i can't
really find is a simple socket server that accepts multiple connections.. Can
anyone help? If i missed some valuable information online please let me know
because i am pulling my hair out..

Any help is much appreciated,

Andesay


Answer: Say, you want to run a server accepting client connections on port 9000:

    
    
    from twisted.internet import reactor, protocol
    
    PORT = 9000
    
    class MyServer(protocol.Protocol):
        pass
    
    class MyServerFactory(protocol.Factory):
        protocol = MyServer
    
    factory = MyServerFactory()
    reactor.listenTCP(PORT, factory)
    reactor.run()
    

And if you want to test connecting to this server, here's the code for a
client (to launch in a different terminal):

    
    
    from twisted.internet import reactor, protocol
    
    HOST = 'localhost'
    PORT = 9000
    
    class MyClient(protocol.Protocol):
        def connectionMade(self):
            print "connected!"
    
    class MyClientFactory(protocol.ClientFactory):
        protocol = MyClient
    
    factory = MyClientFactory()
    reactor.connectTCP(HOST, PORT, factory)
    
    reactor.run()
    

You'll notice the code is very similar, only we use a Factory for a server and
a ClientFactory for a client, and the servers needs to listen (listenTCP)
while the client needs to connect (connectTCP). Good luck!

