By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,360 Members | 1,299 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,360 IT Pros & Developers. It's quick & easy.

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

P: 4
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.

Expand|Select|Wrap|Line Numbers
  1. import Queue
  2. import threading
  3. import time 
  4. import socket 
  6. queue = Queue.Queue()
  8. class ThreadClient(threading.Thread):
  9.     def __init__(self, queue, client):
  10.         threading.Thread.__init__(self)
  11.         self.queue = queue
  12.         self.client = client 
  14.     def run(self):
  16.         print "Got connection from %s"% str(self.client.getpeername())
  18.         while True:
  19.             #Grab message from the queue
  20.             data = self.client.recv(2342)
  21.             self.queue.put(data)
  23.             host = self.queue.get()
  25.             self.client.send(str(host))
  27.             #singing task 
  28.             self.queue.task_done()
  29.         self.client.close()
  31. def main():     
  32.     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  33.     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
  34.     s.bind(("", 1110))
  35.     print "Waiting for clients"
  36.     while True:
  37.       s.listen(5)
  38.       client , address = s.accept()
  39.       D = ThreadClient(queue, client)
  40.       D.setDaemon(True)
  41.       D.start()
  43.     queue.join()
  44. main()
Oct 4 '12 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.