Python套接字错误:不是套接字的对象
在这里,当初始化实例时,我对初始化套接字感到困惑,我使用它在循环中通过它传输数据Python套接字错误:不是套接字的对象,python,sockets,Python,Sockets,在这里,当初始化实例时,我对初始化套接字感到困惑,我使用它在循环中通过它传输数据 class Server2: host = "localhost" port = 44444 s = "" sock = "" addr = "" def __init__(self,voitingSistem,voitingInterfece,voiting,sql): self.s = socket.socket(socket.AF_INET,
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()
错误:
试图对不是套接字的对象执行操作
以下条件始终为真,除非
buf
等于exit
,否则代码将始终执行:
elif buf:
self.sock.send(buf)
print(buf.decode('utf8'))
self.sock.close()
在前面的代码中,您可以通过调用self.sock.recv(1024)获得buf
。对于阻塞模式下的普通套接字,它将返回至少一个字节。在任何情况下,buf
都不会为空。程序执行将被简单地阻止,直到一些数据到达。如果发生了非常糟糕的事情,比如断开连接,您将收到异常通知,而不是接收空缓冲区
因此,基本上是在接收到第一块数据后关闭与客户端的连接。我相信您的意思是在
==“exit”
部分使用self.sock.close()
。这是哪一行发生的?程序接收第一个数据。但是下一位数据会因为这样的错误而崩溃。请在粘贴中正确缩进代码。(主回路前缺少4个空格)。此外,还需要整个stacktrace来帮助您。