Python 2.6 Chat Loop Issue. Cant Receive And Send Simultaneously

前端 未结 3 1738
别那么骄傲
别那么骄傲 2021-01-25 02:54

Im trying to make a console chat program, but have a problem with my loop. I cant get input and receive the other persons input at the same time. If two message or more are sent

3条回答
  •  青春惊慌失措
    2021-01-25 03:28

    The Twisted framework can be used to help accomplish this task. The code below initiates a chat server that clients can then connect to and communicate back and forth, based off of the server instance settings. You can make the appropriate modifications to fit your requirements:

    from twisted.internet.protocol import Factory
    from twisted.protocols.basic import LineReceiver
    from twisted.internet import reactor
    
    class Chat(LineReceiver):
    
        def __init__(self, users):
            self.users = users
            self.name = None
            self.state = "GETNAME"
    
        def connectionMade(self):
            self.sendLine("What's your name?")
    
        def connectionLost(self, reason):
            if self.users.has_key(self.name):
                del self.users[self.name]
    
        def lineReceived(self, line):
            if self.state == "GETNAME":
                self.handle_GETNAME(line)
            else:
                self.handle_CHAT(line)
    
        def handle_GETNAME(self, name):
            if self.users.has_key(name):
                self.sendLine("Name taken, please choose another.")
                return
            self.sendLine("Welcome, %s!" % (name,))
            self.name = name
            self.users[name] = self
            self.state = "CHAT"
    
        def handle_CHAT(self, message):
            message = "<%s> %s" % (self.name, message)
            for name, protocol in self.users.iteritems():
                if ':' in message:
                    self.exc(message.split(':')[0])
                if protocol != self:
                    protocol.sendLine(message)
    
        def exc(self, cmd):
            print cmd
            if cmd == 'who':
                for i in self.users:
                    print i
    
    
    class ChatFactory(Factory):
    
        def __init__(self):
            self.users = {} # maps user names to Chat instances
    
        def buildProtocol(self, addr):
            return Chat(self.users)
    
    
    reactor.listenTCP(8123, ChatFactory())
    reactor.run()
    

提交回复
热议问题