Answer the question
In order to leave comments, you need to log in
Multithreading Python3. How to terminate script execution when the command to do so comes?
I am learning python. For training, I write a client-server. A lot of clients connect to the north, they communicate with it. But now the admin has connected to the server and he sends the command "adminexit" to the server to completely shut down the server. I tried to do it, but it does not work, the script does not end. Please tell me how to make it work.
#!/usr/bin/env python3
import socket
from threading import Thread, current_thread
host = "localhost"
port = 1605
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen(5)
print("ready")
running=True
def clientthread(conn):
while True:
global running
buf = conn.recv(1024)
buf = buf.rstrip()
if buf.decode('utf8') == "exit":
conn.send(b"bye")
break
elif buf.decode('utf8') == "get":
conn.send(b"data")
elif buf.decode('utf8') == "adminexit":
conn.send(b"EXIT!")
running=False
break
else:
conn.send(b"listen")
while True:
if running==True:
conn, addr = sock.accept()
print("client connected with address " + addr[0])
conn.send(b"hello!")
ht = Thread(target=clientthread, args=(conn,))
ht.start()
else:
break
conn.close()
sock.close
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question