Stop python script from executing

I have below python script ( server.py ) to listen on the port and grab requests from the client. I am calling this script from another python file ( Main.py ). My requirement is to terminate server.py after a certain time. I tried to use exit () on the last line of the file - server.py to stop the server and stop the execution of the file, however I could not stop the script from starting and the server kept responding. Can someone help me in telling me where I am going wrong.

Server.py

bind_ip = "127.0.0.1"
bind_port = 2530

def servercreate():
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind((bind_ip,bind_port))
    server.listen(5)

    while True:
        client, addr = server.accept()
        print('[*] Accepted connection from: %s:%d' % (addr[0], addr[1]))
        client_handler = threading.Thread(target=handle_client, args=(client,))
        client_handler.start()


def handle_client(client_socket):
    request = client_socket.recv(2056)
    print('[*] Received: %s' % request)

    message = "{}"
    client_socket.send(message.encode('utf-8'))
    client_socket.close()

if __name__ == '__main__':
    servercreate()

Main.py

import Server
Server.servercreate()
+4
source share
1 answer

, time.sleep(, , ), :

import time
timeout = time.time() + 10

while True:
    print ('hello')
    if time.time() > timeout:
        print ('program terminated')
        break

10 :

timeout = time.time() + 60*10   

, , -

import time

x=0
while True:
    print ('waiting 5')
    time.sleep(5)
    x += 1
    if x == (10):
        break

time.sleep ,

:

import time


bind_ip = "127.0.0.1"
bind_port = 2530

def servercreate():

    #put minutes of time you want program to run for below
    minutes = 10
    timeout = time.time() + (60*minutes)

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind((bind_ip,bind_port))
    server.listen(5)

    while True:
        client, addr = server.accept()
        print('[*] Accepted connection from: %s:%d' % (addr[0], addr[1]))
        client_handler = threading.Thread(target=handle_client, args=(client,))
        client_handler.start()
        if time.time() > timeout:
            break


def handle_client(client_socket):
    request = client_socket.recv(2056)
    print('[*] Received: %s' % request)

    message = "{}"
    client_socket.send(message.encode('utf-8'))
    client_socket.close()


if __name__ == '__main__':
    servercreate()
+3

Source: https://habr.com/ru/post/1674428/


All Articles