gpt4 book ai didi

python - 无法关闭 KeyboardInterrupt 上的套接字

转载 作者:太空狗 更新时间:2023-10-29 22:25:38 25 4
gpt4 key购买 nike

from socket import socket, AF_INET, SOCK_STREAM

sock = socket(AF_INET, SOCK_STREAM)
sock.bind(("localhost", 7777))
sock.listen(1)
while True:
try:
connection, address = sock.accept()
print("connected from " + address)
received_message = sock.recv(300)
if not received_message:
break
connection.sendall(b"hello")

except KeyBoardInterrupt:
connection.close()

所以我试着把我的头围在套接字上,并拥有这个非常简单的脚本但出于某种原因,我无法使用 KeyboardInterrupt

终止此脚本

我如何使用 KeyboardInterrupt 终止脚本,为什么我不能使用 KeyboardInterrupt 终止脚本?

最佳答案

  1. break 以退出 while 循环。没有break,循环不会结束。
  2. 为了安全起见,请检查是否设置了connection

from socket import socket, AF_INET, SOCK_STREAM

sock = socket(AF_INET, SOCK_STREAM)
sock.bind(("localhost", 7777))
sock.listen(1)
while True:
connection = None # <---
try:
connection, address = sock.accept()
print("connected from ", address)
received_message = connection.recv(300)
if not received_message:
break
connection.sendall(b"hello")
except KeyboardInterrupt:
if connection: # <---
connection.close()
break # <---

更新

  • 有一个拼写错误:KeyBoardInterrupt 应该是 KeyboardInterrupt
  • sock.recv 应该是 connection.recv

关于python - 无法关闭 KeyboardInterrupt 上的套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34871191/

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