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
杀死脚本? 最佳答案
break
以摆脱while
循环。没有break
,循环将不会结束。 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
。