'Threaded tcp server in python does not exit on SIGINT
I am having hard time trying to figure out how to accept input while maintaining the listener method running to keep on receiving new connections
I tried to create a function that creates an object of the TcpServer and used that function as the target of a daemon thread but it does not seem to help because when I import the class in a python interpreter and manually running the listener method the shell gets stuck and even ctrl+c does not help and I am left with the only method of killing the process from taskmanager which is annoying to do every time I change the code
I also tried to set the daemon to True but this does not solve the problem
new = TcpServer()
new.daemon = True
How do you run the listener method in a way that allows me to accepts user input from the shell (as commands to the server) and to be able to kill it typing exit as a command
import socket
import sys
from threading import Thread, Lock
from time import sleep
class TcpServer(Thread):
def __init__(self, host="0.0.0.0", port=6666 ):
Thread.__init__(self)
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((host,port))
self.listen = True
self.threads_lst = []
def listener(self, n=5):
self.server.listen(n)
while self.listen:
c, addr = self.server.accept()
print(f"{addr[0]} connected over port {addr[1]}")
lock = Lock()
client_thread = Thread(target=self.client_connection, args=(c,addr,lock,), daemon=True )
self.threads_lst.append(client_thread)
client_thread.start()
def client_connection(self, c, addr, lock):
lock.acquire()
while True:
data = c.recv(4096)
if not data:
break
print(data.decode())
c.close()
lock.release()
return
What do I have to add/modify to be able to accept user input from shell using cmd = input('Input your action : ')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
