How to "generate" multiple TCP clients using Threads in the same script?

1

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 to "generate" multiple TCP clients using Threads instead of opening multiple terminal instances and running the script multiple times.

    
asked by anonymous 17.08.2016 / 21:31

1 answer

1
Just create the thread. Creating threads in python depends only on creating a class inheriting the Thread class, quite simple, see the example. link

In your case you'll get something like the code below:

from threading import Thread
from socket import *

class ThreadSocket(Thread):

    def __init__ (self):
        Thread.__init__(self)

    def run(self):
        '''seu código aqui'''

t1 = ThreadSocket()
t2 = ThreadSocket()
t3 = ThreadSocket()
t1.start()
t2.start()
t3.start()
    
05.05.2017 / 23:05