Mp0int
Mp0int

Reputation: 18727

Handling socket process in a class in Python

I am using Python 2.6 and new to sockets and threads.

I need to write a socket code for listinging certain ports. Following is my related socket class:

class SocketServer(object):
    """
    """
    def __init__(self, host, sock_port, buffsize=1024):
        self.hostname = host
        self.sock_port = sock_port
        self.buffsize = buffsize
        self.socket = None

    def start(self):
        print "Listening: "
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind((self.hostname, self.sock_port))
        self.socket.listen(10)

        while True:
            conn, address = self.socket.accept()
            thread.start_new_thread(handle_data, (conn, self.buffsize))

if __name__ == "__main__":
    server = socketServer(ip, port)
    try:
        server.start()
    except Exception as e:
        print e

handle_data is the function that listens to relatted certain port:

def handle_data(conn, buffsize):
    while True:
        try:
            _veri = conn.recv(buffsize)
            if not _veri:
                break
        except Exception as e:
            break
        # Do something else
    conn.close()

It all works fine, but handle_data have some long code so I want to write it as a class.

First question is, whow can I write it as a class? Second, threading a class in socket listening have any disadventages (considerable memory usage difference etc.) ove threading a function?

Upvotes: 1

Views: 274

Answers (1)

Raito
Raito

Reputation: 1573

There is no difference between threading a class and threading a function.

Basically, every thread that you'll start will run a function.

Then, threading a class implies to write a class with a entry point function, which will manage your instance. All you will have to write is:

thread.start_new_thread(myClassInstance.handle_data, (conn, self.buffsize))

The only difference is that using a class, you'll have a very very low overhead due to the self argument passed to every method call you do. I think that at this point, you can neglect it.

Upvotes: 1

Related Questions