user9280940
user9280940

Reputation:

Python3 socket exception handling

I would like to do a simple while loop to connect to an echo server with exception handling but i don't know why the try seems to but execute only once event though it's in a while loop Here is the code:

if len(argv) ==3:
    ip=argv[1]
    port=int(argv[2])
    print("Server: ",ip," on port ",port)
else:
    ip=input("IP: ")
    port=int(input("Port: "))

while True:
    try:
        client_socket.connect((ip, port))
        break
    except sk.error:
        print("connection error")
        choice=input("[r]etry, [c]hange server details, [q]uit ?")
        if choice == "c":
            ip=input("IP: ")
            port=int(input("Port: "))

I would if the user enter c, prompt him to enter new values and go back in the try to connect to the server.

Update: No removing the break makes the loop goes infinite even if the connection succeed.

The right ip is: 192.168.0.100 and port: 9090

[user@User-MacBook-Pro Python]$python3 echo_client4.py
IP: 192.168.0.100
Port: 9090
connection error
[r]etry, [c]hange server details, [q]uit ? 

[root@centos_school Python]# python3 echo_server3.py 9090
Server listener on port  9090
Accept client request from:  ('192.168.0.149', 51839)

Upvotes: 1

Views: 322

Answers (1)

vgro
vgro

Reputation: 488

It exits because of the 'break' statement, as it leaves your while loop after the first execution. I think you might have wanted to use 'continue' so that the loop quits the current iteration and moves on to the next one.

Upvotes: 1

Related Questions