簡體   English   中英

readline() AttributeError,Python3.4 問題

[英]readline() AttributeError, Python3.4 issue

在這段代碼中, readline 和 writeline 根本不起作用,而運行代碼控制台顯示:
線程 Thread-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')

仔細觀察你的縮進。 readline() (和writeline() )函數就是這樣,一個全局函數。 它不是您的ClientThread類的一部分,因為您的縮進不匹配。 如果您在某些行上使用制表符並在其他行上使用空格進行縮進,則將制表符大小設置為 8 個空格,或者最好不要使用制表符。 Python 風格指南推薦后者。

這是 Martijn Pieters 評論的副本。 我把它作為一個答案,因為它似乎是最完整的回應。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM