Search code examples
pythontwisted

How to manage connections and Clients in Twisted?


I started working with Twisted Framework, I wrote a TCP server and I connect to it throw Telnet, it works fine. Now I want to manage connections and connected clients( sending data, cutting connections, etc etc) using an GUI like PyUI or GTK..

this is my code

import sys
import os
from twisted.internet import reactor, protocol
from twisted.python import log

    class Server(protocol.Protocol):

        def dataReceived(self, data):
            log.msg ("data received: %s"%data)
            self.transport.write("you sent: %s"%data)

        def connectionMade(self):
            self.client_host = self.transport.getPeer().host
            self.client_port = self.transport.getPeer().port
            if len(self.factory.clients) >= self.factory.clients_max:
                log.msg("Too many connections !!")
                self.transport.write("Too many connections, sorry\n")
                self.transport.loseConnection()
            else:
                self.factory.clients.append((self.client_host,self.client_port))
                log.msg("connection from %s:%s\n"%(self.client_host,str(self.client_port)))
                self.transport.write(
                        "Welcome %s:%s\n" %(self.client_host,str(self.client_port)))


        def connectionLost(self, reason):
            log.msg('Connection lost from %s:%s. Reason: %s\n' % (self.client_host,str(self.client_port),reason.getErrorMessage()))
            if (self.client_host,self.client_port) in self.factory.clients:
                self.factory.clients.remove((self.client_host,self.client_port))

    class MyFactory(protocol.ServerFactory):

        protocol = Server
        def __init__(self, clients_max=10):
            self.clients_max = clients_max
            self.clients = []          


    def main():
        """This runs the protocol on port 8000"""
        log.startLogging(sys.stdout)
        reactor.listenTCP(8000,MyFactory)
        reactor.run()


    if __name__ == '__main__':
        main()

Thanks.


Solution

  • If you want to write a single Python program (process) that runs both your UI and your networking, you will first need to choose an appropriate Twisted reactor that integrates with the UI toolkit's event loop. See here.

    Next, you might start with something simple, like have a button that when pressed will send a text message to all currently connected clients.

    Another thing: what clients will connect? Browsers (also)? If so, you might contemplate about using WebSocket instead of raw TCP.