What I am trying to do is get a letter from the client, send it to server, have the server make some changes and send it back. And then I want the client to display it. But I am having trouble making this into a loop. I want it to continuously ask for a letter until win is equal to true. How can I do that? I tried adding a while loop in the server side but got an error about a bad file descriptor. Thank you!
Client:
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()
Server:
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()

whiledidnt break and tries to send it again, on a closed connection, giving you that error. You have no way of knowing which letters he has guessed, you have no loops on the client side, you do not listen to the initial empty word in the client side.