如何排除此错误:OSError:[Errno 9]错误的文件描述符

2024-05-06 03:21:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图找出我的客户机和服务器文件之间的问题来自何处。客户端接收TCP服务器完成的正确计算。但是,TCP服务器在执行任务后继续抛出错误

添加服务器.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

添加客户端.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


Tags: toinpy服务器addhostfordata
1条回答
网友
1楼 · 发布于 2024-05-06 03:21:44

您正在关闭此行中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() 

相关问题 更多 >