2016-10-02 50 views
0

我一直在有一個程序,無論何時有人按下輸入鍵,不輸入內容,程序將停止輸入。下面Python 3套接字應用程序停止發送數據

#Client 
import socket 
from time import sleep 
import time 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

host = 'localhost' 
port = 9990 

s.connect((host, port)) 

print('connecting') 

global ab 

try: 
    ab = input('enter input') 
except Exception as eb: 
    ab = 'hello' 
s.sendall(ab.encode()) 

while True: 
    global hi 
    try: 
     hi = input('enter input') 
    except Exception as b: 
     hi = input('enter input') 

    try: 
     dataNew = s.recv(4024) 
     s.sendall(hi.encode()) 

    except Exception as be: 
     print('try again') 

    if dataNew: 
     print(dataNew) 

    if not dataNew: 
     print('error') 
     break 

服務器:

#Server 
import socket 

host = 'localhost' 
port = 9990 

try: 
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
except Exception as e: 
    print("Error creating socket") 

try: 
    s.bind((host, port)) 
    print('Binding socket') 
    s.listen(10) 
    print('listening') 
except Exception as e: 
    print('Error creating server') 

def mainInput(): 
    while True: 
     try: 

      dataNew = c.recv(4024) 
      c.sendall(dataNew) 
      if not dataNew: 

       print('waiting or disconnected') 
       break 

      if dataNew: 
       print(dataNew, a) 

     except Exception as b: 
      print('error') 

def mainLoop(): 
    while True: 
     global c 
     global a 
     c, a = s.accept() 
     print('Connected by', a) 
     mainInput() 

mainLoop() 

的問題是,進入一個空白的消息打破了計劃。

回答

0

這裏的主要問題是,你打電話input()假設你會得到回報。但如果用戶只是按下回車鍵,該函數將返回一個空字符串(input去掉換行符)。一個空字符串中有零個字符。如果您向套接字寫入零字符,則不會發送任何內容(TCP是面向流的協議,並且不遵守「消息」邊界,因此零字節的send本質上是無操作的[儘管 - 如果連接已知處於關閉或關閉狀態 - 仍然可以生成異常])。所以客戶端什麼都不發送,然後嘗試從服務器讀取回顯的響應。但服務器從來沒有收到任何東西,所以服務器仍然在等待recv,並永遠不會到達它自己的sendall。所以現在客戶也在等待(永遠)在recv

在代碼中的其他問題:

如果您在服務器設置中檢測到錯誤,你應該退出,而不是僅僅打印消息,並繼續進行,因爲後續的操作依賴於先前操作的結果。同樣,如果您在服務器中遇到異常,您應該從循環中斷開而不是繼續,因爲如果您繼續嘗試在斷開連接的狀態下嘗試操作套接字,通常只會在異常之後發生異常。

如果recv返回一個空字符串,就意味着對方已經關閉(或shutdown)的連接,所以你應該立即退出循環,而不是試圖在字符串sendall,因爲(即使字符串是空的如上所述),這可能會產生一個例外。

相關問題