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

Asked

Viewed 506 times

1

I wrote the code of 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 me opening multiple instances of the terminal and running the script multiple times.

  • Have you tried creating a class that sets all these socket settings and deploys it using threads? https://docs.python.org/3/library/threading.html

1 answer

1


Just create the thread. Creating threads in python depends only on creating a class inheriting the Thread class, very simple, see the example. https://imasters.com.br/artigo/20127/py/threads-em-python/? trace=1519021197&source=single

In your case you will 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()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.