无法在KeyboardInterrupt [Python]上关闭套接字

Zio*_*ion 7 python sockets

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()
Run Code Online (Sandbox Code Playgroud)

所以我试图把我的头包裹在套接字并拥有这个非常简单的脚本,但出于某种原因,我不能用a杀死这个脚本 KeyboardInterrupt

我怎么用KeyboardInterrupt 那个杀死脚本,为什么我不能用它杀死它KeyboardInterrupt

fal*_*tru 5

  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  # <---
Run Code Online (Sandbox Code Playgroud)

更新

  • 有一个错字:KeyBoardInterrupt应该是KeyboardInterrupt
  • sock.recv应该是connection.recv

  • 这很奇怪,因为。运行它仍然不会用`CTRL-C`关闭脚本 (8认同)

Han*_*mov 5

尝试使用timeout使程序周期性地从等待进程中“跳出”accept来接收KeyboardInterrupt命令。

这是套接字服务器的示例:

import socket

host = "127.0.0.1"
port = 23333

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.bind((host,port))
sock.listen()

sock.settimeout(0.5)

print("> Listening {}:{} ...".format(host,port))

try:
    while True:
        try:
            conn, addr = sock.accept()
            data = conn.recv(1024)
            if not data:
                print("x Client disconnected!")
                # break
            else:
                print("> Message from client: {}".format(data.decode()))
                msg = "> Message from server".format(data.decode()).encode()
                conn.sendall(msg)
        except socket.timeout:
            # print("Timeout")
            pass
        except KeyboardInterrupt:
            pass
except KeyboardInterrupt:
    print("Server closed with KeyboardInterrupt!")
    sock.close()
Run Code Online (Sandbox Code Playgroud)