2017-07-30 74 views
0

這裏我很困惑,在初始化實例時初始化套接字,我使用它在循環中通過它傳輸數據。Python套接字錯誤:一個不是套接字的對象

class Server2: 
    host = "localhost" 
    port = 44444 
    s = "" 
    sock = "" 
    addr = "" 


    def __init__(self,voitingSistem,voitingInterfece,voiting,sql): 
     self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
     self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
     self.s.bind((self.host, self.port)) 
     self.s.listen(5) 
     self.sock, self.addr =self.s.accept() 
     self.client = WorkWithClient() 
     self.voitingSistem = voitingSistem() 
     self.voitingInterfece = voitingInterfece() 
     self.voiting = Voiting("d") 
     super().__init__() 

    def mainLoop(self): 
     while True: 
      buf = self.sock.recv(1024) # receive and decode a command 
      print("getting command: "+(buf.decode('utf8'))) 
      ansver = self.client.AcceptCommand(buf.decode('utf8')) # act upon the command 

      if buf.decode('utf8') == "exit": 
       self.sock.send("bye") 
       break 
      elif buf: 
       self.sock.send(buf) 
       print(buf.decode('utf8')) 
       self.sock.close() 

錯誤:

An attempt was made to perform an operation on an object that is not a socket

+1

哪條線發生了這種情況? –

+0

程序收到第一個數據。但是,接下來的一些數據會出現這樣的錯誤。 – Dmitry

+0

請在您的貼上正確地縮進您的代碼。 (在mainLoop之前缺少4個空格)。此外,它將需要整個堆棧跟蹤幫助你。 –

回答

1

以下條件始終爲真,代碼將始終執行,除非buf等於exit

elif buf: 
    self.sock.send(buf) 
    print(buf.decode('utf8')) 
    self.sock.close() 

代碼前面已經獲得buf通過調用self.sock.recv(1024)。對於通常在阻塞模式下的套接字,它將返回至少一個字節。沒有任何情況下buf將是空的。程序執行將被阻止,直到某些數據到達。如果發生非常糟糕的情況,例如斷開連接,您將收到異常通知,而不是通過接收空的緩衝區。

因此,基本上,您在收到第一個數據塊後關閉與客戶端的連接。我相信你的意思是self.sock.close()== 'exit'部分。