Python循环中的套接字程序

时间:2017-10-16 12:24:52

标签: python sockets

我要做的是从客户端获取一封信,将其发送到服务器,让服务器进行一些更改并将其发回。然后我希望客户端显示它。但我无法将其变成循环。我想让它不断要求一封信,直到胜利等于真。我怎样才能做到这一点?我尝试在服务器端添加一个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()

1 个答案:

答案 0 :(得分:1)

此序列图可帮助您构建应用。尝试根据图表修改您的程序,并告诉我们您发现了什么问题。

Sequence Diagram