简体   繁体   中英

Using TCP Client to send multiple messages in Python

I have many TCP clients that needs to send multiple messages to a server. On the server side, I wrote:

def listenConnections():
    thread_recieve = Thread(target=recieveInstruction)

    while(1):
        lstn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # port = int(sys.argv[1]) # server port number

        lstn.bind(('IP', PORT))


        lstn.listen(5)

        global clnt
        (clnt,ap) = lstn.accept()

       thread_recieve.start()

def recieveInstruction():
    while (1):
        try:
            message = clnt.recv(1024)
            print message
        except:
            pass

So what happens is, every time one client connects he is able to send 1 message and the server reads it. But when another client connects or the same client tries to send another message it doesn't work. The client side is pretty solid, I can't seem to know how to get to use the connection that is created multiple times to be able to receive messages. That is why I tried multithreads, but that didn't work either. Btw, I run listenConnections on a thread also. I do:

def main():

    t = Thread(target=listenConnections)

    t.start()

main()

First of all, the lstn.bind(('IP', PORT)) and lstn.listen(5) methods should be called only once, outside the loop. Inside the loop, you should call only (clnt,ap) = lstn.accept() .

Besides, you are instantiating a new thread to listen do clients messages only ONCE, outside the loop, so you will only be able to call thread_receive.start() ONCE, the second time you try to do this, it will probably throw an error, since this thread will be already started. You have to create a new thread for EACH client connection, which means calling thread_receive = Thread(target=receiveInstruction) every time, before calling thread_receive.start() .

It is also recommendable that you keep some sort of internal control of clients and connections, in order to be able to manage which messages were received from or should be sent to which clients.

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