I'm building something that when it receives a message from a server via socket, it plays something on my computer and does some other stuff. But when I try to make it be able to capture ctrl+c and gracefully disconnect by alerting the server that it's disconnecting, it only works when a message has been received. If I try to press ctrl + c while it's waiting for a message (while it's on message = sock.recv(1024).decode()), it only ends the script and sends the disconnect message to the server after it received a message. So basically, I'm having a problem where the code under except KeyboardInterrupt only executes after a line of code has completed, so I have to wait until a function has been completed or I receive a message from the server for it to disconnect. What's going on here, and how do I fix it?
Here's my very simple client code:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('192.168.0.102', 65535))
while True:
try:
message = sock.recv(1024).decode()
print(message)
if message != 'Nothing, just normal console preorder message':
# stuff happens here
pass
except KeyboardInterrupt:
break
sock.send('DISCONNECTING'.encode())
Forgot to mention: Ran basically the exact same script on my Mac, and it worked as expected, but I only had this problem on my Windows machine. Not sure if that matters or not.