Python Thread.start()导致AttributeError

时间:2014-01-03 00:19:22

标签: python multithreading attributeerror

在python中编写客户端 - 服务器系统时,我在服务器标准输出中遇到了一个奇怪的错误,这不应该发生:

Traceback (most recent call last):
  File "C:\Users\Adam\Drive\DJdaemon\Server\main.py", line 33, in <module>
    ClientThread(csock, addr).start()
AttributeError: 'ClientThread' object has no attribute '_initialized'

我将这条线分成多行,而导致错误的是start()。

有什么想法吗?这是服务器源代码 - 客户端只是打开并关闭连接:

import socket, threading

class ClientThread(threading.Thread):
    def __init__(self, sock, addr):
        self.sock = sock
        self.addr = addr
    def run(self):
        sock = self.sock
        addr = self.addr

        while True:
            msg = sock.recv(1024).decode()
            if not msg:
                print('Disconnect: ' + addr[0] + ':' + str(addr[1]))
                sock.close()
                return

# Constants
SERVER_ADDRESS = ('', 25566)
MAX_CLIENTS = 10
MCSRV_ADDRESS = ('localhost', 25567)

srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.bind(SERVER_ADDRESS)
srv.listen(MAX_CLIENTS)

udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

while True:
    (csock, addr) = srv.accept()
    print('Connect: ' + addr[0] + ':' + str(addr[1]))
    ClientThread(csock, addr).start()

1 个答案:

答案 0 :(得分:5)

您忘记在ClientThread中调用__init__的父构造函数。

def __init__(self, sock, addr):
    super(ClientThread, self).__init__()
    self.sock = sock
    self.addr = addr