1
我正在IDLE中的服務器和客戶端之間運行的猜數字遊戲。我用兩個while循環,如下所示:雖然服務器和客戶端之間的循環(Python)
服務器:
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()
客戶:
#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()
用戶應該有三次機會,以獲得數權利。但是,目前的設置只允許用戶由於某種原因進行一次猜測。在此之後,服務器的while循環停止發送指令,因此用戶無法猜測。我該如何解決?
爲什麼你要在每次迭代中創建並連接一個新套接字? – 2014-10-16 11:03:58