[英]How do I troubleshoot this error: OSError: [Errno 9] Bad file descriptor
I am trying to figure out where the problem is coming from between my client and server files.我试图找出问题出在我的客户端和服务器文件之间的位置。 The client receives the correct calculation done by the TCP server.
客户端接收由 TCP 服务器完成的正确计算。 However, the TCP server continues to throw an error after performing the task.
但是,TCP 服务器在执行任务后继续抛出错误。
add_server.py添加服务器.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添加客户端.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
Full traceback完整追溯
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
You are closing the socket inside the while
loop in this line您正在关闭此行中
while
循环内的套接字
while True:
data = conn.recv(1024)
# Rest of the code
conn.close()
So the next time you try to receive the data with conn.recv
it results in an error.因此,下次您尝试使用
conn.recv
接收数据时,它会导致错误。
To fix this simply close the connection after you're done receiving all the data.要解决此问题,只需在接收完所有数据后关闭连接即可。
while True:
data = conn.recv(1024)
# Rest of the code
conn.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.