Home > Software engineering >  Code will not continue after breaking from a while loop receiving client data
Code will not continue after breaking from a while loop receiving client data

Time:11-30

I have created a client/server setup for transferring PGP signature information from the client to the server. The code below shows part of the server code, where adds signatures received from the client to an output text file

However, my code isn't able to move on after the second while loop, after breaking. It receives 2 signatures from the client, and successfully prints the "test" string only twice and adds both received strings to the output file, but the program will not continue after breaking, and doesn't print the other "test2" and "test3" strings.

while True:

    # Accepts incoming connection, creating socket used for data transfer to client
    conn, addr = server.accept()

    print("Connected successfully")

    directory = "(Hidden for question)"

    outputFile = open((directory   "\\signatures.txt"), "w")

    while True:
        data = conn.recv(2048)
        if not data: break
        print("test")
        outputFile.write(data.decode() "\n")
        outputFile.flush()

    print("test2")

    conn.close()

print("test3")

I feel like I am missing something very obvious but cannot figure out what the issue is.

CodePudding user response:

Your loop will never break as the recv function on a socket is a blocking call. This means the function will not return until it receives some data, there for not data will always be false.

Try sending more information (after the first 2 signatures) into the socket and see that your script will continue to write it into the file.

If you want to receive a specific amount of data/times, track it using a variable and break your loop using that.

CodePudding user response:

Alternatively to @Nadav's answer, remove the inner while loop. Since recv() is synchronous, you don't need to loop.

  • Related