如何解决此错误:OSError: [Errno 9] Bad file descriptor
Posted
技术标签:
【中文标题】如何解决此错误:OSError: [Errno 9] Bad file descriptor【英文标题】:How do I troubleshoot this error: OSError: [Errno 9] Bad file descriptor 【发布时间】:2021-12-05 11:02:22 【问题描述】:我试图找出问题出在我的客户端和服务器文件之间的位置。客户端收到 TCP 服务器完成的正确计算。但是,TCP 服务器在执行完任务后继续抛出错误。
add_server.py
# This is add_server.py script
import socket
host = socket.gethostname()
port = 8096
s = socket.socket()
s.bind((host, port))
s.listen(5)
print('Waiting for connection...')
conn, addr = s.accept()
while True:
data = conn.recv(1024) # Receive data in bytes
print(data)
decoded_data = data.decode('utf-8') # Decode data from bystes to string
print(data)
d = decoded_data.split(",") # Split the received string using ',' as separator and store in list 'd'
add_data = int(d[0]) + int(d[1]) # add the content after converting to 'int'
conn.sendall(str(add_data).encode('utf-8')) # Stringify results and convert to bytes for transmission (String conversion is a must)
conn.close() # Close connection
add_client.py
# This add_client.py script
import socket
host = socket.gethostname()
port = 8096
s = socket.socket()
s.connect((host, port))
a = input('Enter first number: ')
b = input('Enter second number: ')
c = a + ', ' + b # Generate string from numbers
print('Sending string to sever for processing...'.format(c))
s.sendall(c.encode('utf-8')) # Converst string to bytes for transmission
data = s.recv(1024).decode('utf-8') # Receive server response (addition results) and convert from bystes to string
print(data) # Convert 'string' data to 'int'
s.close() # close connection
完整追溯
Traceback (most recent call last):
File "/home/sharhan/AWS/AWS-PERSONAL-COURSES/linux-networking-and-troubleshooting/python-networking/add_server.py", line 17, in <module>
data = conn.recv(1024) # Receive data in bytes
OSError: [Errno 9] Bad file descriptor
【问题讨论】:
【参考方案1】:您正在关闭此行中 while
循环内的套接字
while True:
data = conn.recv(1024)
# Rest of the code
conn.close()
因此,下次您尝试使用conn.recv
接收数据时,会导致错误。
要解决此问题,只需在接收完所有数据后关闭连接即可。
while True:
data = conn.recv(1024)
# Rest of the code
conn.close()
【讨论】:
好的。我这样做了,它引发了另一个错误: Traceback(最近一次调用最后一次):文件“/home/sharhan/AWS/AWS-PERSONAL-COURSES/linux-networking-and-troubleshooting/python-networking/add_server.py”,行22、inprint(d)
以查看正在发送的数据
它是空的。相当令人惊讶。但我认为我正在拆分的数据存储在变量“d”中。请问我怎么会错过没有存储在变量“d”中的数据。想不通以上是关于如何解决此错误:OSError: [Errno 9] Bad file descriptor的主要内容,如果未能解决你的问题,请参考以下文章
在使用python语言的open函数时,提示错误OSError: [Errno 22] Invalid argument: ‘文件路径’
pyaudio-OSError: [Errno -9999] 意外主机错误
如何解决:OSError: Unable to create file (unable to open file: name = ‘. et_classification.h5‘, errno = 2