简体   繁体   中英

While loops between servers and clients (Python)

I'm making a number guessing game that runs between a server and a client in IDLE. I'm using two while loops, as follows:

Server:

l = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#Generate random number
integer = random.randrange(1, 10)

l.bind(("127.0.0.1", 4001)) 
l.listen(5)

while True: 
    (s, ca) = l.accept()

     #Send instruction to client
     s.send("What is your guess? ".encode())

     #Receive guess from client
     y = s.recv(4096).decode()

     #Break out of the loop if the guess was correct
     if int(y) == integer:
        break

s.close()

Client:

#User gets 3 guesses
for x in range(0, int(chances)):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    s.connect(("127.0.0.1", 4001))

    #Get instruction from server and make a guess
    y = input(s.recv(80).decode())

    #Guess a number and send it to the server
    s.send(y.encode())

s.close()   

The user should have 3 chances to get the number right. However, the current setup only lets the user guess once for some reason. After this the server's while loop stops sending instructions and so the user cannot make a guess. How do I fix this?

The only problem I could find is that the line

s.send(y.encode())

raised an exception and should instead be

s.send(str(y).encode())

Everything else worked fine (it gave me 3 guesses as expected)

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