Anna Belle
Anna Belle

Reputation: 7

Python client-server socket error [Errno 9] Bad file descriptor

I wrote a simple client-server echo program that does the following:

  1. Client sends values x, y, z, degree, timestamp.
  2. Server receives these values (as strings) and parses them into floats.
  3. Server sends back ((x/2), (y/2), (z/2) (degree/2))
  4. Client receives data and prints it back.

The program is performing as it should, but once the client echoes back the values, I keep getting the following error:

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 174, in _dummy raise error(EBADF, 'Bad file descriptor') socket.error: [Errno 9] Bad file descriptor

I'm new to python, so I'm not sure what could be causing it. I read that it could relate to the way I close the connection and socket, but I thought I did it correctly. Any help to find and fix the error (and help me learn more about python) is appreciated! Here's my server, which is giving me the error:

    import socket


    HOST = '127.0.0.1'
    PORT = 56789

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((HOST, PORT))
    s.listen(1)
    conn, addr = s.accept()
    print('Connection address: ', addr)
    Message = ''
    while 1:
        data = conn.recv(1024)
        if not data:
            break
        print('Received data: ', data)
        List = data.split(',')
        x = float(List[0]) / 2.0
        y = float(List[1]) / 2.0
        z = float(List[2]) / 2.0
        degree = float(List[3]) / 2.0
        Message = str(x) + ', '
        Message += str(y) + ', '
        Message += str(z) + ', '
        Message += str(degree)
        conn.send(Message)
        conn.close()
        s.close()

Upvotes: 0

Views: 4948

Answers (1)

Asav Patel
Asav Patel

Reputation: 1162

you are closing your socket connection in while loop.

so you would be able to receive the data on the first iteration of the loop. and after that you have closed the connection. now on next iteration you are trying to read data from that connection again using

data = conn.recv(1024)

but your connection is already closed. so you would receive that error. move

conn.close()
s.close()

out of your while loop.

Upvotes: 0

Related Questions