我知道我们可以按CTRL + C来中断程序,但是当我尝试在套接字上侦听的程序无法执行此操作(可能仅在Windows上)。因此,我尝试找到解决方法,但是没有用:
import sys, socket, time, msvcrt, threading
msg = ".:::SERVER:::."
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 8881))
s.listen(5)
def start_server():
while True:
print("Waiting for connections...")
(conn, addr) = s.accept()
print("Connection with:", addr[0])
conn.send(bytes(str(len(msg)), "UTF-8"))
conn.send(bytes(msg, "UTF-8"))
conn.close()
t = threading.Thread(target = start_server)
t.start()
key = msvcrt.getwch()
print(key)
if key == 'z':
sys.exit(0)