gpt4 book ai didi

python - 不退出python套接字程序

转载 作者:行者123 更新时间:2023-12-03 12:08:55 25 4
gpt4 key购买 nike

我有以下python UDP套接字客户端。我想在按crtl + c时退出程序,但是由于该线程没有发生,我该如何解决?

import socket
from threading import Thread
import signal
import sys
message = "well"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('127.0.0.1', 3447)
def sighandler(signum, frame):
# Close the server
global sock
print 'Shutting down server...'
# Close existing client socket
sock.close()
signal.signal(signal.SIGINT, sighandler)

def recv():
while True:
print "Waiting to receive data"
data, server = sock.recvfrom(4096)
print "Server : ", server
print "data : ", data
Thread(target=recv).start()

try:
while True:
message = raw_input()
print >>sys.stderr, 'sending "%s"' % message
sent = sock.sendto(message, server_address)
except:
import traceback; traceback.print_exc();

finally:
sock.close()

最佳答案

有时,您在线程中所需的全部是:

t = Thread(target=recv)
# Daemon runs in background, and main can respond to ctrl-c.
t.daemon = True
t.start()

关于python - 不退出python套接字程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46809972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com