[英]Socket Program in Python Looping
我正在尝试做的是从客户端收到一封信,将其发送到服务器,让服务器进行一些更改然后发回。 然后我要客户端显示它。 但是我很难将其循环。 我希望它不断索要一封信,直到赢等于真。 我怎样才能做到这一点? 我尝试在服务器端添加一个while循环,但收到有关错误文件描述符的错误。 谢谢!
客户:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.