2017-07-30 68 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'部分。