Python TTP Connection

I have a python tcp server, there is a stream for each connection to listen on. When I call close in case of a connection object exception, a "bad file descriptor" is generated. From googling, I found several solutions, each of which uses a loop to receive client data and interrupt this loop when they decide to disconnect the client. My client is written in C # and doesn’t “get” that it is “disconnected” from the server, python simply ignores incoming data from the C # client. What is the legal, best way to disable tcp connection from server side in python?

Thanks in advance

+4
source share
2 answers

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

Here are some thoughts on common practices. For the client, one way to find out if it is disconnected is to check if the recv () value is 0. If so, it means that the remote side has closed the connection. Basically, you should use select (or poll) and pass the fds of all clients and server to select. If you get a read event on any of the fds, then depending on the type of fd, this is what happens. If fd is a server type, then a read event means that there is a pending connection, and you must send accept () to get a new connection. On the other hand, if hte fd is not a server type (which means a regular tcp connection), then a read event means there is some data, and you should throw a recv () event to read the data.

You must use a loop to select. Basically, start the loop using the select () call, and as soon as you get the event, do something with this event, and then re-run the loop and issue the next select (). You may find these links useful: http://ilab.cs.byu.edu/python/select/echoserver.html and http://docs.python.org/2/library/socket.html

+2
source

From the docs :

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

So you must call shutdown() before calling close() . You must also pass the SHUT_RDWR flag to completely disconnect 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).

+1
source

Source: https://habr.com/ru/post/1500004/


All Articles