Paul Sigonoso Paul Sigonoso - 3 months ago 9
Python Question

How "generate " multiple TCP clients using Threads instead of opening multiple instances of the terminal and run the script several times?

I wrote the code for a simple TCP client:

from socket import *

# Configurações de conexão do servidor
# O nome do servidor pode ser o endereço de
# IP ou o domínio (ola.python.net)
serverHost = 'localhost'#ip do servidor
serverPort = 50008

# Mensagem a ser mandada codificada em bytes
menssagem = [b'Ola mundo da internet!']

# Criamos o socket e o conectamos ao servidor
sockobj = socket(AF_INET, SOCK_STREAM)
sockobj.connect((serverHost, serverPort))

# Mandamos a menssagem linha por linha
for linha in menssagem:
sockobj.send(linha)

# Depois de mandar uma linha esperamos uma resposta
# do servidor
data = sockobj.recv(1024)
print('Cliente recebeu:', data)

# Fechamos a conexão
sockobj.close()


I would like to know, how " generate " multiple clients TCP using Threads instead of opening multiple instances of the terminal and run the script several times.

Alu Alu
Answer

Try this: The worker method will be set as target for the thread. So every thread will use the code of the method. After starting all thread, the for loop at the bottom will wait for all threads to finish.

In the worker method you can use arrays or lists of data from outside the method. So you can iterate for example over a list of Urls or append the fetched data to a new output array.

import threading

threads = []
maxNrOfThreads = 5

def worker():
    do_stuff()

for _ in range(maxNrOfThreads):
    thr = threading.Thread(target=worker)
    threads.append(thr)
    thr.setDaemon(True)
    thr.start()

for thread in threads:
    thread.join()