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

标签 python sockets makefile ioerror

我想使用 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另一个地方的文件。但同时,排除套接字s从第一 with这样套接字就不会关闭。
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")

关于关闭文件上的 Python 套接字 Makefile 错误 I/O 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65019161/

相关文章:

Python函数封装(以避免在没有适当上下文的情况下意外调用)

python - opencv 训练分类器从不连续 3 阶段

使用 sha256 验证的 python 套接字文件传输不起作用,但只是有时?

makefile - 多个目标名称具有相同的结果?

c++ - 有目的地多次链接同一个对象时,如何避免多个定义错误?

python - 正则表达式返回 true 且日文字符不正确

python - Scrapy 帖子数据

c# - 用于 Telnet 的 TcpClient Stream streamReader.ReadToEnd()

iOS 客户端,C++ 服务器?

Bash:Makefile 中的 for 循环:意外的文件结尾