sam hassan
sam hassan

Reputation: 217

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. However, the TCP server continues to throw an error after performing the task.

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

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

Upvotes: 0

Views: 4541

Answers (1)

kinshukdua
kinshukdua

Reputation: 1994

You are closing the socket inside the while loop in this line

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.

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() 

Upvotes: 1

Related Questions