我想使用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())
或在另一个地方重新创建write
并read
归档。但同时,请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")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句