readline()AttributeError,Python3.4版本

readline()AttributeError,Python3.4版本,python,python-3.x,Python,Python 3.x,在这段代码中,readline和writeline根本不起作用,而运行代码控制台时显示: 线程1中的异常: AttributeError:“ClientThread”对象没有属性“readline” def run(self): # Thread's main loop. Once this function returns, the thread is finished and dies. global QUIT # Need to declare QUIT as global,

在这段代码中,readline和writeline根本不起作用,而运行代码控制台时显示:
线程1中的异常: AttributeError:“ClientThread”对象没有属性“readline”

def run(self):  # Thread's main loop. Once this function returns, the thread is finished and dies.
    global QUIT  # Need to declare QUIT as global, since the method can change it/
    done = False
    cmd = self.readline()  #Read data from the socket and process it
    while not done:
        if 'quit' == cmd:
            self.writeline('Ok, bye')
            QUIT = True
            done = True
        elif 'bye' == cmd:
            self.writeline('Ok, bye')
            done = True
        else:
            self.writeline(self.name)

        cmd = self.readline()

    self.client.close()  # Make sure socket is closed when we're done with it
    return
以上是违规代码

整个代码如下,看到任何问题,可以为我解决这个问题,请让我知道。先谢谢你

import sys
import socket
import threading
import time

QUIT = False


class ClientThread(threading.Thread):  # Class that implements the client threads in this server
    def __init__(self, client_sock):  # Initialize the object, save the socket that this thread will use.
        threading.Thread.__init__(self)
        self.client = client_sock

    def run(self):  # Thread's main loop. Once this function returns, the thread is finished and dies.
            global QUIT  # Need to declare QUIT as global, since the method can change it/
        done = False
        cmd = self.readline()  #Read data from the socket and process it

        while not done:
            if 'quit' == cmd:
                self.writeline('Ok, bye')
                QUIT = True
                done = True
            elif 'bye' == cmd:
                self.writeline('Ok, bye')
                done = True
            else:
                self.writeline(self.name)

            cmd = self.readline()

        self.client.close()  # Make sure socket is closed when we're done with it
        return


def readline(self):  # Helper function, read up to 1024 chars from the socket, and returns them as a string
    result = self.client.recv(1024)
    if None != result:  # All letters in lower case and without and end of line markers
        result = result.strip().lower()
    return result


def writeline(self, text):  # Helper function, writes the given string to the socket with and end of line marker at end
    self.client.send(text.strip() + '\n')


class Server:  # Server class. Opens up a socket and listens for incoming connections.
    def __init__(self):  # Every time a new connection arrives, new thread object is created and
        self.sock = None  # defers the processing of the connection to it
        self.thread_list = []

    def run(self):  # Server main loop: Creates the server (incoming) socket, listens > creates thread to handle it
        all_good = False
        try_count = 0  # Attempt to open the socket
        while not all_good:
            if 3 < try_count:  # Tried more than 3 times without success, maybe post is in use by another program
                sys.exit(1)
            try:
                self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # Create the socket
                port = 80
                self.sock.bind(('127.0.0.1', port))  # Bind to the interface and port we want to listen on
                self.sock.listen(5)
                all_good = True
                break
            except socket.error:
                print('Socket connection error... Waiting 10 seconds to retry.')
                del self.sock
                time.sleep(10)
                try_count += 1

        print( 'Server is listening for incoming connections.')
        print('Try to connect through the command line with:')
        print('telnet localhost 80')
        print('and then type whatever you want.')
        print()
        print("typing 'bye' finishes the thread. but not the server",)
        print("eg. you can quit telnet, run it again and get a different ",)
        print("thread name")
        print("typing 'quit' finishes the server")

        try:
            while not QUIT:
                try:
                    self.sock.settimeout(0.500)
                    client = self.sock.accept()[0]
                except socket.timeout:
                    time.sleep(1)
                    if QUIT:
                        print('Received quit command. Shutting down...')
                        break
                    continue
                new_thread = ClientThread(client)
                print('Incoming Connection. Started thread ',)
                print(new_thread.getName())
                self.thread_list.append(new_thread)
                new_thread.start()
                for thread in self.thread_list:
                    if not thread.isAlive():
                        self.thread_list.remove(thread)
                        thread.join()
        except KeyboardInterrupt:
            print('Ctrl+C pressed... Shutting Down')
        except Exception as err:
            print('Exception caught: %s\nClosing...' % err)
        for thread in self.thread_list:
            thread.join(1.0)
            self.sock.close()

if "__main__" == __name__:
    server = Server()
    server.run()

print('Terminated')
导入系统 导入套接字 导入线程 导入时间 退出=错误 类ClientThread(threading.Thread):#在该服务器中实现客户端线程的类 def uu init(self,client_sock):#初始化对象,保存此线程将使用的套接字。 threading.Thread.\uuuuu init\uuuuuu(自) self.client=client\u sock def run(self):#线程的主循环。一旦此函数返回,线程就结束并消亡。 全局退出#需要将退出声明为全局,因为该方法可以更改它/ 完成=错误 cmd=self.readline()#从套接字读取数据并进行处理 虽然没有这样做: 如果“退出”==cmd: self.writeline('好,再见') 退出=真 完成=正确 elif'bye'==cmd: self.writeline('好,再见') 完成=正确 其他: self.writeline(self.name) cmd=self.readline() self.client.close() 返回 def readline(self):#Helper函数,从套接字读取最多1024个字符,并以字符串形式返回 结果=self.client.recv(1024) 如果没有!=结果:#所有字母均小写,不带行尾标记 结果=结果.strip().lower() 返回结果 def writeline(self,text):#Helper函数,将给定字符串写入套接字,并在末尾加上行尾标记 self.client.send(text.strip()+'\n') 类服务器:#服务器类。打开套接字并侦听传入的连接。 def uu init uu(self):#每次新连接到达时,都会创建新的线程对象并 self.sock=None#延迟对其连接的处理 self.thread_list=[] def run(self):#服务器主循环:创建服务器(传入)套接字,侦听>创建线程来处理它 一切都好=错误 尝试_count=0#尝试打开套接字 虽然并非都是好的: 如果3仔细查看缩进。
readline()
(和
writeline()
)函数就是一个全局函数。它不是
ClientThread
类的一部分,因为缩进不匹配。如果在某些行上使用制表符,在其他行上使用空格进行缩进,则将制表符大小设置为8个空格,或者更好的做法是完全不使用制表符。Python样式指南推荐后者


这是Martijn Pieters评论的副本。我正在回答这个问题,因为这似乎是最完整的回答。

仔细看看你的缩进。
readline()
(和
writeline()
)函数就是一个全局函数。它不是
ClientThread
类的一部分,因为缩进不匹配。如果在某些行上使用制表符,在其他行上使用空格进行缩进,则将制表符大小设置为8个空格,或者更好的做法是完全不使用制表符。Python样式指南推荐后者


这是Martijn Pieters评论的副本。我正在回答这个问题,因为这似乎是最完整的回答。

仔细看看你的缩进。
readline()
函数就是一个