Python 2.6 Chat Loop Issue. Cant Receive And Send Simultaneously

前端 未结 3 1767
别那么骄傲
别那么骄傲 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:48

    Threading isn't as hard as you think, and mastering it is an invaluable addition to your toolchest.

    Just make a class that is a subclass of Thread and make sure it has a run() method. then instantiate the class and call its start() method.

    Making the thread stop is more difficult to do right. Best to set a flag and make sure you check it regularly in your while loop, hence you need a timeout on your blocking recv(), of, say, 1 second.

    from socket import *
    from threading import Thread
    
    
    #Get User Info
    Ip = raw_input('IP>>>')
    Port = int(raw_input('Port>>>'))
    User = raw_input('Username>>>')
    
    #Open Socket To Server
    EncCon = socket(AF_INET, SOCK_STREAM)
    EncCon.connect((Ip, Port))
    
    print '\nStarting Chat....'
    print '\n<-------------------------------------------->\n\n'
    
    
    class ReceiveThread(Thread):
    
        def __init__(self, sock):
            Thread.__init__(self)
            self.sock = sock
            self.shouldstop = False
    
        def run(self):
            self.sock.settimeout(1)
            while not self.shouldstop:
                try:
                    data = self.sock.read()
                    print data
                except socket.timeout:
                    continue
    
        def stop(self):
            self.shouldstop = True
    
    
    # start receive loop:
    r = ReceiveThread(EncCon).start()
    
    
    #Send Loop
    while 1:
        MsgOut = raw_input()
        if MsgOut: EncCon.send(MsgOut)
    
        if MsgOut == '.':
            r.stop()
            r.join()
    
    
    EncCon.close()
    

    Now, this program still has the original problem that it would be impossible to start two instances, as you do not listen, but immediately connect. But that, I believe, was not the main part of your question.

提交回复
热议问题