gpt4 book ai didi

Python Thread.start() 导致 AttributeError

转载 作者:行者123 更新时间:2023-11-28 21:56:47 25 4
gpt4 key购买 nike

在用 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()

最佳答案

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

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

关于Python Thread.start() 导致 AttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20894377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com