Where are the connections stored, are they in a list, how to I access them?
I have a (-messy-) program that will allow the users to set there name and when they send input to the server it will come up with "Received: Blah from username" but I would like to send that to all of the people who are connected.
Also, So that they can shut the connection to them.

from twisted.internet import reactor, protocol

PORT = 6661

class User(protocol.Protocol):
    
    connectionstat = 1
    name = ""
    
    def connectionMade(self):
        self.transport.write("Hello, What is your name?")
    
    def dataReceived(self, data):
        if self.connectionstat == 1:
            self.name = data
            self.connectionstat = 2
        else:
            print "Received: " + data.rstrip('\n') + " from " + self.name
            self.transport.write("You Sent: " + data)


def main():
    factory = protocol.ServerFactory()
    factory.protocol = User
    reactor.listenTCP(PORT,factory)
    print "Running Echo..."
    reactor.run()

if __name__ == '__main__':
    main()

Thanks

Dani AI

Generated

Good call, — the ServerFactory is exactly where to keep the set of active connections so every Protocol instance can reach them via self.factory. Store protocol instances (not raw transports) and broadcast from the factory; remove each instance on disconnect to avoid leaks.

Example: a small line-based chat using LineReceiver (Python 3-style, so bytes are used). It keeps clients in a set, sets a name on first line, broadcasts messages to others, and cleanly removes clients on connectionLost:

from twisted.internet import reactor, protocol
from twisted.protocols.basic import LineReceiver

class ChatFactory(protocol.Factory):
    def __init__(self):
        self.clients = set()

class Chat(LineReceiver):
    def connectionMade(self):
        self.name = None
        self.factory.clients.add(self)
        self.sendLine(b"Please enter your name:")

    def connectionLost(self, reason):
        self.factory.clients.discard(self)

    def lineReceived(self, line):
        text = line.decode('utf-8').strip()
        if self.name is None:
            self.name = text
            self.sendLine(("Welcome, %s" % self.name).encode('utf-8'))
            for c in list(self.factory.clients):
                if c is not self and getattr(c, 'name', None):
                    c.sendLine(("%s joined" % self.name).encode('utf-8'))
            return
        if text == "/quit":
            self.transport.loseConnection()
            return
        msg = ("%s: %s" % (self.name, text)).encode('utf-8')
        for c in list(self.factory.clients):
            if c is not self:
                c.sendLine(msg)

# in main: factory = ChatFactory(); factory.protocol = Chat; reactor.listenTCP(PORT, factory)

Notes and quick tips:

  • Use list(self.factory.clients) when iterating so removing clients during iteration is safe.
  • In Python 3 Twisted uses bytes on transports; encode/decode as shown. On Python 2 you can send Unicode directly.
  • For simple text protocols LineReceiver saves parsing work. Always discard or remove the client in connectionLost to prevent memory leaks.

Sorry I forgot about Factorys

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.