Python 套接字 Makefile 错误 I/O 对已关闭文件的操作

Python Socket Makefile Error I/O operation on closed file

我想使用 socket.makefile 方法而不是 socket.send 或 socket.recv 但我在关闭文件时遇到此错误 I/O 操作。

from socket import *

s = socket(AF_INET,SOCK_STREAM)
s.connect(('localhost',4321))
read = s.makefile('r',)
write = s.makefile('w')

def send(cmd):
    # print(cmd)
    write.write(cmd + '\n')
    write.flush()

with s,read,write:
    send('TEST')
    send('LIST')
    while True:
        send("DONE")
        data = read.readline()
        if not data: break
        item = data.strip()
        if item == 'DONE':
            break
        elif item.startswith("--player-"):
            print(f"player{item.split('--player-')[1]}")
        print(f'item: {item}')
    send('OTHER') 
send("GGGGGGGG")  #I want to send this part in another place .I dont want to in with s,read,write:
print(read.readline().strip())

提前感谢您的帮助。

with 语句有这样的行为:

with s,read,write:
    # smth to do
# <--------------- s, read and write are closed here

因此在关闭的对象上调用后续发送。

您不需要使用 with 语句:

# ...
send('TEST')
send('LIST')
while True:
    send("DONE")
    data = read.readline()
    if not data: break
    item = data.strip()
    if item == 'DONE':
        break
    elif item.startswith("--player-"):
        print(f"player{item.split('--player-')[1]}")
    print(f'item: {item}')
send('OTHER')
send("GGGGGGGG")  # write is open here
print(read.readline().strip())

或者在另一个地方重新创建 writeread 文件。但同时,排除第一个with中的sockets,使socket不关闭

with read, write:  # <-- s excluded
    send('TEST')
    send('LIST')
    while True:
        send("DONE")
        data = read.readline()
        if not data: break
        item = data.strip()
        if item == 'DONE':
            break
        elif item.startswith("--player-"):
            print(f"player{item.split('--player-')[1]}")
        print(f'item: {item}')
    send('OTHER')
# ...
read = s.makefile('r', )  # <-- recreate files
write = s.makefile('w')
send("GGGGGGGG")