简体   繁体   中英

Python close tcp connection

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM