2017-10-16 3 views
0

私がしようとしているのは、クライアントから手紙を受け取り、サーバに送信し、サーバにいくつかの変更を加えて返送させることです。そして、私はクライアントにそれを表示させたい。しかし、私はこれをループにすることに問題があります。私は、勝利が真実に達するまで、継続的に手紙を求めることを望みます。どうやってやるの?私はサーバー側でwhileループを追加しようとしましたが、不正なファイル記述子に関するエラーが発生しました。ありがとうございました!Pythonループでのソケットプログラム

クライアント:

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() 
+0

私たちがテストできる完全な例は表示されていません。 – Adirio

+0

@Adirio私はすべてのコードを追加しました!ありがとうございました! – dani

+0

あなたは彼に '_ _ _ _ _ _ _ _'を送ろうとしていますが、クライアントは聞いていません。クライアントはレターを送信しており、サーバーはそれを受信して​​解読していて、クライアントが受け取っていない文字で新しい単語を形成して印刷してから接続を終了します。一方、サーバは新しい単語を内側の 'while'が再び作り直し、閉じた接続でもう一度それを送信しようとして、あなたにそのエラーを与えます。あなたは彼が推測した文字を知る方法がなく、クライアント側にループがなく、クライアント側の最初の空白の言葉を聞きません。 – Adirio

答えて

1

このシーケンス図は、アプリの構築を支援します。ダイアグラムに従ってプログラムを修正し、見つけた問題を教えてください。

Sequence Diagram

関連する問題