简体   繁体   中英

Exit Python While Loop when socket disconnects

I have a bit of code that receives a WiFi password from a Raspberry Pi. The Pi dishes out a new code every 2 minutes. The script below checks the password and updates the connection with the new password if needed.

        # Create a TCP/IP socket

s=socket(AF_INET, SOCK_DGRAM)


# Bind the socket to the port
s.bind (('',4446))
s.settimeout(10.0)
print ("Listening . . . .")

data=s.recv(1024).decode()
print ("Password:  "+data)
os.system('netsh wlan set profileparameter name=PI_AP Keymaterial='+data)
var1=data

try:
    while 1:
        data=s.recv(1024).decode()
        print ("Password:  "+data)

        if var1!=data:
            os.system('netsh wlan set profileparameter name=PI_AP Keymaterial='+data)
            print ("Password:  "+data)
            var1=data

except socket.timeout:
    print ("Timed Out")

Here is the output, with the error message I am seeing after I disconnect:

>>> ================================ RESTART ================================
>>> 
Listening . . . .
Password:  m9FyvpJCILQrZB4sq125AfUn9nfS9Z6qDlbBxy12pL48y5kJTLrH01osp4xXWN3
Password:  m9FyvpJCILQrZB4sq125AfUn9nfS9Z6qDlbBxy12pL48y5kJTLrH01osp4xXWN3
Password:  m9FyvpJCILQrZB4sq125AfUn9nfS9Z6qDlbBxy12pL48y5kJTLrH01osp4xXWN3
 **Traceback (most recent call last): File "C:\\Users\\cave\\Desktop\\system_V1\\UAD-V1.0.py", line 21, in <module> data=s.recv(1024).decode() socket.timeout: timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\\Users\\cave\\Desktop\\system_V1\\UAD-V1.0.py", line 29, in <module> except socket.timeout: TypeError: catching classes that do not inherit from BaseException is not allowed >>>**

You should receive a socket disconnection exception, or empty data (as you tested in the if) in case of a disconnection.

If you do not receive the exception (which is kinda awkward) you may use the select (low-level) or the selectors (high-level) modules in order to see if you receive data on the line.

You may set a 2 minute timeout which afterwards the select() function will throw an exception.

UPDATE:

In order to catch the timeout exception, wrap your code like this:

try:
    while 1:
        ...
except socket.timeout:
    print("timed out")
...

UPDATE 2:

Seems like you're trying to catch socket.socket.timeout while you need to catch socket.timeout . I believe you used this line on top: from socket import * . If so, try catching timeout and not socket.timeout . That's the reason from ... import * is not recommended.

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