简体   繁体   中英

readline() AttributeError, Python3.4 issue

In this code the readline and writeline doesn't work at all, while running the code Console shows this:
Exception in thread Thread-1: AttributeError: 'ClientThread' object has no attribute '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

Above is the offending code

The whole code is below as follows, see any issues and can solve this for me, let me know please. Thank you in advance

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')

Look closely at your indentation. The readline() (and writeline() )function is just that, a global function. It is not part of your ClientThread class, because your indentation doesn't match. If you are using tabs on some lines and spaces on others for indentation, then set your tab size to 8 spaces, or better yet don't use tabs at all. The Python styleguide recommends the latter.

This is a copy of a comment by Martijn Pieters. I am making it an answer as it seems to be the most complete response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM