这是我的服务器 - 客户端聊天程序中的客户端代码,但是当我尝试通过发送信件 q 来关闭此程序时,它根本不起作用。它停留在终端并等待一些东西。
我在这里做错了什么?
import socket
import threading
import time
receiving = False
lock = threading.Lock()
def receive(name, sock):
receiving = True
while receiving:
try:
lock.acquire()
while True:
data, address = sock.recvfrom(1024)
print str(data)
except:
pass
finally:
lock.release()
host = 'localhost'
port = 0
server = ('localhost', 7787)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
s.setblocking(0)
receiveThread = threading.Thread(target=receive, args=("receiveThread", s))
receiveThread.start()
username = raw_input("Name: ")
message = raw_input(username + "-> ")
while True:
if message == 'q':
receiving = False
receiveThread.join()
s.close()
break
if message != '':
s.sendto(username + ": " + message, server)
lock.acquire()
message = raw_input(username + "-> ")
lock.release()
time.sleep(0.2)
如果您有兴趣查看服务器代码,请访问:
import socket
import threading
import time
host = 'localhost'
port = 7787
running = False
MAX_PACKET_SIZE = 1024
clients = []
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
s.setblocking(0)
running = True
print "server started..."
while running:
try:
data, address = s.recvfrom(MAX_PACKET_SIZE)
if 'quit' in str(data):
running = False
print 'server stopped...'
if address not in clients:
clients.append(address)
print time.ctime(time.time()) + str(address) + ": :" + str(data)
for client in clients:
s.sendto(data, client)
except:
pass
running = False
s.close()
答案 0 :(得分:3)
因为你有一个异常块,除了一切。在这种情况下,它还会捕获键盘中断并覆盖终止呼叫。
你应该为KeyboardInterrupt添加一个单独的catch块:
except KeyboardInterrupt:
raise
答案 1 :(得分:0)
因为在python ctrl + C中触发了KeyboardInterrupt异常被抛出。这使您可以优雅地关闭程序。你用
捕获了这个例外 except:
pass