Reputation: 623
Is there a way to determine if a socket can still be read? I tried isinstance and type but their type are the same as each other even if one has been closed and another is active so I'm trying to figure out how to see if a socket is alive and can be read or used or can not be so I can avoid this error: OSError: [WinError 10038] An operation was attempted on something that is not a socket
Upvotes: 1
Views: 421
Reputation: 94
On windows, you can do this by running the netstat command using the python subprocess module and then parsing the output.
import subprocess
output, error = subprocess.Popen(['netstat','-n'],stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
# then parse the port numbers / states out of the variable *output*
Upvotes: 0
Reputation: 1935
Based on your comment, ruler, I think I know what you're getting at.
What you want to do is break out of your while loop once your data stream reaches the end THEN close the socket after you're said and done. In the past, I have done the folowing:
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
The while loop will remain so long as data streams in (based on the if loop). Otherwise, it will break out of the loop and, finally, close the socket. This way, you won't even have to worry about your socket closing on your mid-loop... just check for your stream and close it once all the data has been received. Hopefully, this helps.
Upvotes: 1