Python 3.4套接字和线程问题

时间:2015-08-10 13:52:21

标签: python-3.x

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, err:
                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')

解决了很多问题,这些是剩下的,谢谢你们!

1st error: socket.error, err.This specifically tells me that this no longer works in Python 3.4, but does not offer an alternative.   
2nd Error: except socket.error, err:  Python 3.4 does not support this syntax  
3rd Error: self.readline(), I also have to assume writeline does not work also.
In this case, self.readline() is totally not working, I get an error that says  AttributeError: 'ClientThread' object has no attribute 'readline'  
This only happens after the thread is created. Console shows:  
Incoming connection. Started thread.  
Thread-1  
Then flags that error.   
4th Error: Cannot get 2to3 to run? Terminal says not recognised as internal command, and python console gives a big FU.

我可以针对以下错误获得任何整改建议吗?

2 个答案:

答案 0 :(得分:0)

有多个问题阻止您的代码在python3

上出现问题
  • 您正在使用python2 print语句,因此您的代码无法在print()为函数的python3上运行。
  • recvsend方法在python3中需要/返回bytes,而不是str
  • 捕获错误的语法是except ExceptionClass as name

答案 1 :(得分:0)

将Python 2代码移植到Python 3的第一步是通过Python附带的2to3程序运行它。

如果您使用2to3选项通过-w运行代码,它将自动解决您的许多问题。

> 2to3 -w --no-diffs socktest1.py

如果你想看看会改变什么,但不改变任何东西;

> 2to3 socktest1.py |less