Making Client threads constantly reading from the Queue for other client messages

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • wangolo
    New Member
    • Aug 2012
    • 4

    #1

    Making Client threads constantly reading from the Queue for other client messages

    Well i have a problem with properly sharing data or messages between client threads when they have connected to the server. Iam trying to create some kind of messaging server or a chat like Server. where the message from one client is placed on the Queue and sent to other client who are connected or sent to new clients who are just connecting.
    I tried to create a Queue object and then received data from Client and put that received data to the Queue and after send that Queue to the connected clients. But this plan failed the server only shares the message in the queue with the client sending it.

    What i want is to make sure that Clients are received and then they are given the Queue object with data and also the client thread should constantly be reading and writing to the Queue. All client threads should shared the same Queue of new messages.
    Here is the code that i tried.

    Code:
    import Queue
    import threading
    import time 
    import socket 
    
    queue = Queue.Queue()
    
    class ThreadClient(threading.Thread):
        def __init__(self, queue, client):
            threading.Thread.__init__(self)
            self.queue = queue
            self.client = client 
            
        def run(self):
            
            print "Got connection from %s"% str(self.client.getpeername())
            
            while True:
                #Grab message from the queue
                data = self.client.recv(2342)
                self.queue.put(data)
                
                host = self.queue.get()
                
                self.client.send(str(host))
                
                #singing task 
                self.queue.task_done()
            self.client.close()
    
    def main():     
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
        s.bind(("", 1110))
        print "Waiting for clients"
        while True:
          s.listen(5)
          client , address = s.accept()
          D = ThreadClient(queue, client)
          D.setDaemon(True)
          D.start()
          
        queue.join()
    main()
    Last edited by bvdet; Oct 4 '12, 03:00 PM. Reason: Embed code in message
Working...