[英]Bad file descriptor error while sending from server - python
嗨,我不知道為什么會發生此錯誤。 我已經輸入了打印語句,並做了一個測試腳本來嘗試找出問題所在,但我不知道為什么它不起作用。
s = None
for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
af, socktype, proto, canonname, sa = res
print ('Listening on', sa)
try:
s = socket.socket(af, socktype, proto)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except socket.error as msg:
s = None
continue
try:
s.bind(sa)
s.listen(1)
except socket.error as msg:
s.close()
s = None
continue
break
if s is None:
print ('could not open socket')
sys.exit(1)
def handler(signum, frame):
s.close()
sys.exit(1)
signal.signal(signal.SIGINT, handler)
while True:
print('Waiting for connection...')
conn, addr = s.accept()
print ('Connection from', addr)
while True:
data = conn.recv(1024)
if not data:
break
print ('data: ' + data.decode('utf-8'))
filetoOpen = data.decode('utf-8')
print('filetoOpen: ' + filetoOpen)
with open (filetoOpen, 'r') as myfile:
contents=myfile.read().replace('\n', '')
print('about to send :\n' + contents)
conn.send(contents.encode('utf-8'))
myfile.close()
conn.close()
s.close()
sys.exit()
當我運行它時,我得到
Traceback (most recent call last):
File "server.py", line 67, in <module>
data = conn.recv(1024)
OSError: [Errno 9] Bad file descriptor
我試過弄亂它,先將信息保存到變量中,然后對其進行谷歌搜索並在線查看,我做了一個測試腳本,
with open ('/u/students/dzhelabori/NWEN241/sample2.txt', 'r') as myfile:
contents=myfile.read().replace('\n', '')
print(contents)
myfile.close()
可以正常工作並打印文件! 因此,當我嘗試僅通過網絡發送文本時,就會發生錯誤...但是為什么它說文件描述符錯誤,我該怎么辦?
您正在關閉連接:
while True:
data = conn.recv(1024)
# ...
conn.close()
在此循環的第一次迭代之后,將關閉連接。 然后下一個迭代,你想recv
從一個封閉的連接。
如果到那時您已經完成了連接,那么為什么會在一段while True
循環中進行連接?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.