Sorin Vladu
Sorin Vladu

Reputation: 1788

Python socket with worker threads

I'm playing with Python to understand basics of client-server and threading programming.

This is my main.py application:

from threading import Thread 
from Server import Server


    class Worker(object):

        def __init__(self, clients):
            #constructor
            self.clients = clients

        def start(self):
            while True:
                print("it work as expected!")
                conn, addr = self.clients.get()
                print( conn.recv(1024) )

    #create a instance of the server
    server = Server()

    #put on a new thread 
    def serverThreadCallback(server):
        server.start()

    def createWorkerCallback():
        worker = Worker(server.getClients())
        worker.start()


    #put the server on a new thread
    serverThread = Thread( target=serverThreadCallback, args=(server, )  )
    serverThread.daemon = True
    serverThread.start()

    '''
    workerThread = Thread(target=createWorkerCallback) 
    workerThread.daemon = True
    workerThread.start()
    '''

and this is my server.py

import socket
import queue


class Server(object):
    '''
    classdocs
    '''
    def __init__(self):
        '''
        Constructor
        '''
        self.clients = queue.Queue() 

    def create(self):
        print("Creating server...")
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR , 1)
        self.socket = server

    def listen(self):
        print("Starting server...")
        self.socket.bind( ("0.0.0.0", 9002) )
        self.socket.listen(10)
        print("Server started. Listening on localhost port 9002")
        while(True): 
            #conn, addr = self.server.accept()
            self.clients.put(self.socket.accept())

    def start(self):
        self.create()
        self.listen()

    def getClients(self):
        return self.clients

When I try to start the server in that thread, the listening method doesn't call. Something goes stuck in create() method from the server.

What I've did wrong?

Upvotes: 1

Views: 1264

Answers (2)

E.Z.
E.Z.

Reputation: 6661

First, there are a couple of syntax errors on the coded you posted:

main.py:

1) Indentation starting from your class declaration is wrong

2) You should call from server import Server (note the module name is server - in lower case)

server.py

3) You should call import Queue (and not import queue)

4) Therefore the call to self.clients = queue.Queue() should become self.clients = Queue.Queue() (the module name is Queue with upper case Q)

Other than that, you have to add a serverThread.join() after serverThread.start(), otherwise the main thread finishes and the program terminates before your server thread has had the chance to start.

Finally, you might want to change the call to accept() inside the thread, such that it times out from time to time to handle Ctrl+C interrupts properly (otherwise you can only finish your program by killing it)

Upvotes: 1

hzgnjupt
hzgnjupt

Reputation: 1

serverThread.daemon = True

Daemon threads are abruptly stopped when Python program exits.
Maybe the listen() method hasn't been called yet.

Upvotes: 0

Related Questions