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
  • 10-08 02:45