How to check if a socket was closed on this end in Python
If by «this end» you meant server-side, this answer should help. If you meant client-side, the following code from this answer should work.
Related Query
- How to check if a socket was closed on this end in Python
- How to implement this in python : Check if a vertex exist, if not, create a new vertex
- Is there a way to check how many days have passed since the program was last opened — Python
- Python — How to check if a Google Spreadsheets was updated
- Python SFTP issue With Sockets Closing — An existing connection was forcibly closed by the remote host (10054) — How to continue? Breaks process,
- How to parse this web page (and convert into a dictionary) in Python
- Using python how to execute this code concurrently for multiple files?
- How to use Beautiful Soup to extract info out of this in Python
- How can I use a Python streaming socket as a proxy?
- How to translate this bit of Python to idiomatic Javascript
- how to convert a simple python code weekday check
- How can I use Python to get the contents inside of this span tag?
- Python imports-Need someone to check this please
- How to fix this dll loading python error?
- Can somebody explain, how this python code works which prints the heart in Instagram
- Julia vs Python implementation for https://projecteuler.net/problem=2. This was very strange to me and I don’t know where I am messing up in Julia
- how to avoid nested loop in python and check condition on all combination of elements in multi list
- How would I shorten this few lines of python code?
- How to use IN to check if an element is inside a string and avoid to compare duplicate element with Python
- How to ADD PEOPLE TO THIS PROJECT using python in Google Cloud?
- How to check or print padding done in python (keras)?
- How to send the data from one computer to another device on the same WiFi network via python socket program?
- How to fix the python chatbot code problem ‘Attempted to use a closed Session.’
- How to fix this issue ‘TimeoutException’ is not defined in Python Selenium?
- Remove multiple keys and values with its nested dictionary then arrange keys in this “0”,“1”,“2”,“3” order like it was before in Python
- How to solve this else syntax error in python
- How do I interpret this python dependency tree?
- How to handle urllib.error.URLError: ?
- How to suppress gcloud connection closed warning when executed from python
- How to fix this problem in python in pytube?
- How do I append at the end of row in in google sheets using python
- How can I add a new Entry field with a Button? The Entry field was created by a loop in Python Tkinter
- How is this Python design pattern called?
- How can I add this value to a list that was previously a dictionary?
- How to check if a page content is loaded in Python using urllib?
- Python OS Error: A socket operation was attempted to an unreachable network
- How to Type Check in Python when Dictionary has different data Type
- How to reverse iteration once it reaches the end python
- How can I end this game
- Python & Selenium: How do I check if I liked a post on instagram or not?
- How to check if a 2D point is inside or outside a 2D Closed Bezier Curve using Python?
- python — This part makes the code repeat twice, how can I fix it
- I dont know how to deal with this python error TypeError: ‘tuple’ object is not callable
- Check what group was used in python argparse
- OSError: [WinError 10038] An operation was attempted on something that is not a socket — Python sockets?
- How to know scroll bar is at end in selenium python
- How python adds atributes to class in this code?
- Check how long function is currently running Python
- How do I evaluate this equation in z3 for python
- Response [412] when using the requests python package to access this webpage, how to get around it?
More Query from same tag
- Python import working on host but not inside a VM
- How to link Python code with HTML webpage?
- Python official name for an attribute that is not a method
- Fill Multiple empty values in python dictionary for particular key all over dictionary
- Cleaning raw price data from an API that’s received in dictionary format (Python)
- Change field names in Python WTForms
- Why I can’t send messages in a @tasks.loop in discord.py?
- How to iterate through the zeroth index for every item in list in Python
- How do I loop my python code for Twitter API v2 recent search?
- How to read and create new FoxPro 2.6 database table using Python dbf library
- How do I retrieve the text between those
- Dynamically Recreate Include File With SCons
- How to insert a javascript in a single Sphinx page?
- Python ABC classes: One of multiple methods has to be overridden
- Fibonacci — six most significant digits (right most) of very large n numbers
- Sum multiple columns in SQLAlchemy
- How can I set an instance variable as a fileHandle in python?
- on calling a function which returns a dictionary more than once it returns empty dictionary. why is this happening and how can i fix it
- issue transforming Python dictionary of one-itemed list to dictionary of floats
- Load json file with Amazon Alexa
- How can I disable the return_bind_key in PySimpleGui?
- Regex: Negating entire word instead of 1 character
- Python and Dynamics CRM: using a web api
- Cast column values to list keeping the order
- how to change the elements of group of lists after a certain index?
- Opencv : How to remove rectangle black box without removing any other characters
- pip: No module name _internal.main
- how to rotate text in the table cell
- Python: Reflecting Image in black borders
- How to check accuracy of LSTM?
- how can i display nested loops using python
- Is python making a copy of my array in «for elem in A[a:b]»?
- My script returns an error when the test isn’t corresponding to the Regex: ‘NoneType’ object has no attribute ‘group’
- using cPickle returns only the first entry in the file
- Calculate a total from numbers produced by a for loop (running total)
How to know the if the socket connection is closed in python?
First, it is worth saying that in most situations it seems best to handle this in the main handler loop where you can simply test for EOF (empty string received by socket.recv() . However, I came across the need to test for this and the following seemed better than passing another callback in to the thread to get this state, etc)
The following is what I am using, but I am very new to this though, so please provide feedback if there is a better or more efficient way to do this and I’ll update this answer.
It seems like the best way to do this is to check getpeername() (testing socket.recv() here is bad since our test would alter the buffer, for example.)
Return the address of the remote endpoint. For IP sockets, the address info is a pair (hostaddr, port).
If this fails it raises a socket.error [Errno 9] Bad file descriptor.
def is_socket_valid(socket_instance): """ Return True if this socket is connected. """ if not socket_instance: return False try: socket_instance.getsockname() except socket.error as err: err_type = err.args[0] if err_type == errno.EBADF: # 9: Bad file descriptor return False try: socket_instance.getpeername() except socket.error as err: err_type = err.args[0] if err_type in [errno.EBADF, errno.ENOTCONN]: # 9: Bad file descriptor. return False # 107: Transport endpoint is not connected return True
Note: I have the first if-check in there because I am testing an attribute that may be None as well.
- This isn’t as explicit as I’d like but in my tests it seems to be accurate.
- The original question mentions wanting to know the reason for not being connected. This doesn’t address that.
Additionally, another answer mentions fileno() returns a negative number if the local side of the socket is closed. I get the same error 9. Either way, this doesn’t test the other side in the case that this is valid.
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>> s.fileno() 10 >>> s.close() >>> s.fileno() --------------------------------------------------------------------------- error Traceback (most recent call last) ----> 1 s.fileno() /tools/package/python/2.7.13/lib/python2.7/socket.pyc in meth(name, self, *args) 226 227 def meth(name,self,*args): --> 228 return getattr(self._sock,name)(*args) 229 230 for _m in _socketmethods: /tools/package/python/2.7.13/lib/python2.7/socket.pyc in _dummy(*args) 172 __slots__ = [] 173 def _dummy(*args): --> 174 raise error(EBADF, 'Bad file descriptor') 175 # All _delegate_methods must also be initialized here. 176 send = recv = recv_into = sendto = recvfrom = recvfrom_into = _dummy error: [Errno 9] Bad file descriptor
This will give a True/False answer.
Check if socket is closed python
Subreddit for posting questions and asking for general advice about your python code.
Hi so I have this Python socket chat program and how would I know when a client has disconnected?
What i have so far: I am running a daemon thread on each client connected to my server, it’s called «handle» because it’s handling each client/socket individually in a thread.
clients = [] #active clients nicknames = [] #active nicknames def handle(client): «»»This function will be run on every connected client, and will be recieving messages and broadcasting them to all clients connected.»»» while True: try: message = client.recv(1024).decode(‘utf-8’) print(f’Recieved ‘) broadcast(message) #for broadcasting to all clients connected the message except: print(‘something went wrong. ‘) tmp = client # A temp variable for refering to client after removal client.close() #close connection to client nickname = nicknames[clients.index(client)] clients.remove(client) #remove the client from active clients broadcast(f’ has left the chat!’) nicknames.remove(nickname) #remove the nickname from active nicknames break
So it will run in a daemon thread on every connected client/socket and will wait for a message to be recieved and then send the message to all other clients connected. The problem I am facing is that when ever a client disconnects it spams «recieved » in the console. So apparently the client sends empty bytes strings to the server after the client’s program have been terminated, but what I think should happen is that
message = client.recv(1024).decode(‘utf-8’) should raise an exception, and then trigger the exception block whenever a client disconnects, instead of recieving empty byte strings.
So my question is why is it not raising an exception and running the exception block?