0
我想要做的是從客戶端獲取一封信,將其發送到服務器,讓服務器進行一些更改並將其發回。然後我希望客戶端顯示它。但是我很難將它變成一個循環。我希望它不斷要求一封信,直到勝利等於真。我怎樣才能做到這一點?我試圖在服務器端添加一個while循環,但得到了關於錯誤文件描述符的錯誤。謝謝!Python中的Socket編程循環
客戶:
import sys
from socket import *
if sys.argv.__len__() != 3:
serverName = 'localhost'
serverPort = 5555
else:
serverName = sys.argv[1]
serverPort = int(sys.argv[2])
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
# Get letter from user
letter = input('Guess a letter: ')
# Sends letter
letterBytes = letter.encode('utf-8')
clientSocket.send(letterBytes)
#Recieves newWord
newWordInBytes = clientSocket.recv(1024)
newWord = newWordInBytes.decode('utf-8')
print(newWord)
clientSocket.close()
服務器:
import sys
from socket import *
if sys.argv.__len__() != 2:
serverPort = 5555
else:
serverPort = int(sys.argv[1])
# This is a welcome socket
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serverSocket.bind(('', serverPort))
# Listener begins listening
serverSocket.listen(1)
print("The server is ready to receive")
#Set secret word
word = 'arkansas'
linesForString = ' '
#Prints out number of letters
for x in word:
linesForString += '_ '
while 1:
# Wait for connection and create a new socket
# It blocks here waiting for connection
connectionSocket, addr = serverSocket.accept()
win = ' '
#Sends lines of words
linesInBytes = linesForString.encode('utf-8')
connectionSocket.send(linesInBytes)
while 1:
# Receives Letter
letter = connectionSocket.recv(1024)
letterString = letter.decode('utf-8')
win = False
while win == False:
newWord = ' '
for x in word:
if(letterString == x):
newWord += x
else:
newWord += '_ '
#Sends newWord
newWordInBytes = newWord.encode('utf-8')
connectionSocket.send(newWordInBytes)
if(newWord == 'Arkansas'):
win = True
print('You have won the game')
else:
win = False
# Close connection to client but do not close welcome socket
connectionSocket.close()
您沒有顯示我們可以測試的完整示例。 – Adirio
@Adirio我剛添加了我的所有代碼!謝謝! – dani
您正試圖向他發送'_ _ _ _ _ _ _ _',但客戶端沒有收聽。然後客戶端發送一封信,服務器正在接收並解碼它,並形成客戶正在接收和打印的丟失字母的新單詞,然後關閉連接。與此同時,服務器重新將這個新詞作爲內部'while'沒有中斷,並嘗試在關閉的連接上再次發送它,從而爲您提供該錯誤。你無法知道他猜出了哪些字母,客戶端沒有循環,也不會聽到客戶端的初始空白字。 – Adirio