简体   繁体   中英

How to send list from server to client in twisted python?

I am doing a multiclient chat server program in twisted python. In my program, if we send 'list' from one client, server has to send the list of connected clients to that client. Also, when we send 'talk clientname message' from one client, server has to send that message to the destination client specified in the 'clientname'. But my code is not working. there are mistakes in server. Not displays the list and also talk is not working.

My server code is given below:

class MultiEcho(Protocol):

    def __init__(self, factory):
        self.factory = factory

    def connectionMade(self):
        self.factory.clients.append(self)

    def dataReceived(self,data):
        data = data.strip()

        if (data == "list"):
            for client in self.factory.clients:
                print self.factory.clients
                self.transport.write(self.factory.clients)
        else:
            data = data.split()
                    if (len(data) > 1):
                l = data[1]
                m = data[2]
                l.transport.write(m)

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

class MultiEchoFactory(Factory):

    def __init__(self):
        self.clients = []
    def buildProtocol(self, addr):
        return MultiEcho(self)
if __name__ == '__main__':

    import sys
    if len(sys.argv) != 4:
        print "Sorry.. not correct.. Try Again!"
        sys.exit(1)
    else:
        if (sys.argv[1] == "chatserver") and (sys.argv[2] == "-p"):
            PORT = sys.argv[3]
    reactor.listenTCP(8000, MultiEchoFactory())
    reactor.run()   

Can anybody give me a solution, please

  • you can't rely how much data dataReceived() receives. You might need to subclass from LineReceiver and use lineReceived() to process input line by line.
  • transport.write() accepts a string, not a list.

You need to define clientname for a client eg, a factory should be able to find a client given its name. Then you could in LineReceived() :

command, _, rest = line.partition(command_separator)
if command == "talk":
   clientname, _, message = rest.partition(arg_separator)
   self.factory.getClient(clientname).sendLine(message)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM