4

I have a python tcp server, there is thread for every connection to listen. When I call close on connection object exception "bad file descriptor" is thrown. By googling I've found some solutions, each using loop in order to receive client data and breaking that loop, when they decide to disconnect client. My client is written in C# and does not "get", that it's "disconnected" from server, python simply ignores incomming data from C# client. What's the legit, best practice way to disconnect tcp connection from server side in python ?

Thanks in advance

1
  • // , Excellent question! I'm actually quite interested in this. (superuser.com/questions/127863/…) Would you mind showing a link or 8 word summary of one or two of the "loop" solutions you found on search engines? Commented Mar 17, 2016 at 18:25

2 Answers 2

2

A bad file descriptor, most likely, means that the socket was already closed by another thread.

Here are some thoughts on general practices. For the client, one way to know that it is disconnected is to check if the recv() value is 0. If it is, then that means the remote side has closed the connection. Basically, you should use select (or poll) and pass fds of all the clients and teh server to select. If you get a read event on any of the fds, then depending upon the fd type, here is what happens. If the fd is server type, then a read event means that there is a pending connection and you should issue an accept() to get the new connection. On the other hand, if hte fd is a non-server type (meaning a regular tcp connection), then a read event means that there is some data and you should issue a recv() event to read data.

You would use a loop for the select. Basically, start the loop using a select() call and once you get an event, do something with that event, and then reenter the loop and issue the next select(). You might find these links helpful: http://ilab.cs.byu.edu/python/select/echoserver.html and http://docs.python.org/2/library/socket.html

Sign up to request clarification or add additional context in comments.

Comments

2

From the docs:

Note: close() releases the resource associated with a connection but does not necessarily close the connection immediately. If you want to close the connection in a timely fashion, call shutdown() before close().

So you should call shutdown() before calling close(). Also you should pass SHUT_RDWR flag to completely shutdown the connection:

from socket import SHUT_RDWR
...
try:
    s.shutdown(SHUT_RDWR)
    s.close()
except Exception:
    pass

The "bad file description" error means (most likely) that the socket is already closed (at least from Python side).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.