I have just written a very simple udp chatting program for fun. It worked as supposed but now I have no ideas how to safely exit it. It seems that calling sys.exit() is not acceptable due to the problem here: Why does sys.exit() not exit when called inside a thread in Python?
Simply raising signals by ctrl + c will fail because it will be intercepted by raw_input().
Is there any decent way to deal with it?
Here is my code snippet:
import socket
import threading
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
address = ('192.168.1.xxx', 31500)
target_address = ('192.168.1.xxx', 31500)
s.bind(address)
print('waiting for input...')
def rcv():
while True:
data, addr = s.recvfrom(2048)
if not data:
continue
print 'Received: #### ', data
print '\n'
def send():
while True:
msg = raw_input()
if not msg:
continue
s.sendto(msg, target_address)
t1 = threading.Thread(target = rcv)
t2 = threading.Thread(target = send)
t1.start()
t2.start()