October 22, 2024
Chicago 12, Melborne City, USA
python

Socket Timeout Will kill the Thread in Python


I am going to use the following python program in my dedicated online server my doubt is for each and every new connection to server it is creating the new thread number and i already set the timeout function for child it is working fine but the thread number is keep on increasing i thought the thread is not clear properly. kindly give me the solutionto clear or kill the thread process completely.

import socket
from threading import Thread

def on_new_client(client_socket, addr):
while True:
    client_socket.settimeout(10)
    data = client_socket.recv(1024).decode('utf-8')
    client_socket.settimeout(None)
    send="GOK"
    client_socket.send(send.encode())

    if not data:
        print('Disconnected')
        break
    print("Adr and data",addr,data)
client_socket.close()


def main():
host="127.0.0.1"  # allow any incoming connections
port = 4001

s = socket.socket()
s.bind((host, port))  # bind the socket to the port and ip address
s.listen(5)  # wait for new connections

while True:
    c,addr=s.accept()  # Establish connection with client.
    print("New connection from:",addr)
    thread = Thread(target=on_new_client, args=(c, addr))  # create the thread
    thread.start()  # start the thread
c.close() #c.close()
thread.join()


if __name__ == '__main__':
main()



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video