Loop two functions at the same time

Asked

Viewed 75 times

0

I would like to run two functions at the same time in Python, follow my code:

import socket
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import ThreadedFTPServer 
from pyftpdlib.authorizers import DummyAuthorizer



class MyHandler(FTPHandler):

    def on_connect(self):
        print(str(self.remote_ip)+':'+str(self.remote_port), 'se conectou!')

    def on_disconnect(self):
        # do something when client disconnects
        pass

    def on_login(self, username):
        # do something when user login
        pass

    def on_logout(self, username):
        # do something when user logs out
        pass

    def on_file_sent(self, file):
        # do something when a file has been sent
        pass

    def on_file_received(self, file):
        # do something when a file has been received
        pass

    def on_incomplete_file_sent(self, file):
        # do something when a file is partially sent
        pass

    def on_incomplete_file_received(self, file):
        # remove partially uploaded files
        os.remove(file)

def ftp_server():
    authorizer = DummyAuthorizer()
    authorizer.add_user('user', '', '.', perm='elradfmwMT')
    handler = MyHandler
    handler.authorizer = authorizer
    server = ThreadedFTPServer(('10.1.1.127', 21), handler)
    server.serve_forever()

def socket_server():
    host = '' 
    port = 7000 
    addr = (host, port) 
    serv_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serv_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
    serv_socket.bind(addr) 
    serv_socket.listen(10) 
    print('aguardando conexao')
    con, cliente = serv_socket.accept() 
    print('conectado')
    print('aguardando mensagem')
    recebe = con.recv(1024) 
    print('mensagem recebida:'+ recebe)
    serv_socket.close() 

if __name__ == "__main__":
    ftp_server()
    socket_server()
    #Preciso que as duas funções acima funcionem ao mesmo tempo (ou seja, as duas 
    #fiquem ouvindo novas 
    #conexões, tanto FTP, como Socket, e sempre que vier uma conexão, a conexão 
    #deve ser devidamente 
    #atendida e tratada)

How to do this the right way and as simple as possible? I found several more tutorials behind the simplicity I want to do this.

2 answers

3

The initial idea of threading is very simple - and for what you want to do there: two unrelated I/O tasks, each in your thread, is perhaps one of the scenarios where it is simpler to maintain.

In this case only create two objects of the Thread type, and the main argument for these objects is which function will run on that thread (this is the function that will start the thread: of course it can call other functions from inside).

You could organize everything inside the if __name__ == ... there - but it is better to put this logic in a function too:


import threading

...

def main():
    t1 = threading.Thread(target=ftp_server)
    t2 = threading.Thread(target=socket_server)
    t1.start()
    t2.start()
    
    t1.join()
    t2.join()
    
    
if __name__ == "__main__":
    main()

Note that in the call to threading.Thread you cannot call for the function, (putting the () after ftp_server()) - you pass the function itself as parameter. If you put () Python will call the function to try to pass its return value to create the class Thread.

1

You can use Thread

do so:

import threading
import time

if __name__ == "__main__":
    # e na hora de chamar as funcoes:
    x = threading.Thread(target=ftp_server)
    x.start()
    y = threading.Thread(target=socket_server)
    y.start()
    while True:
        time.sleep(60)
        #isso aki he so pra nao sair do cod emquanto ta tudo rodando

Browser other questions tagged

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