简体   繁体   English

服务器和客户端之间的While循环(Python)

[英]While loops between servers and clients (Python)

I'm making a number guessing game that runs between a server and a client in IDLE. 我正在制作一个在IDLE的服务器和客户端之间运行的猜数字游戏。 I'm using two while loops, as follows: 我正在使用两个while循环,如下所示:

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. 用户应该有3次机会获得正确的号码。 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. 此后,服务器的while循环停止发送指令,因此用户无法猜测。 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) 其他一切都正常(它给了我3个预期的猜测)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM