start a multi-sockets server (a socket/per thread) with different ports but same host

zxo102 zxo102 at gmail.com
Sat Aug 12 12:00:02 EDT 2006


Hi,
   I am doing a small project using socket server and thread in python.
 This is first time for me to use socket and thread things.
   Here is my case. I have 20 socket clients.  Each client send a set
of sensor data per second to a socket server.  The socket server will
do two things: 1. write data into a file via bsddb; 2. forward the data
to a GUI written in wxpython.
   I am thinking the code should work as follow (not sure it is
feasible)
      20 threads, each thread takes care of a socket server with a
different port.
   I want all socket servers start up and wait for client connection.
In the attached demo code, It stops at the startup of first socket
server somewhere in the following two lines and waits for client call:

   lstn.listen(5)
   (clnt,ap) = lstn.accept()

  Any ideas how to handle these 20 clients?  Really appreciate your
suggestions.

Thanks a lot.

Ouyang


import socket
import sys
import threading
class srvr(threading.Thread):
   v = ''
   vlock = threading.Lock()
   id = 0  # next available thread number
   def __init__(self,clntsock):
      threading.Thread.__init__(self)
      self.myid = srvr.id
      srvr.id += 1
      self.myclntsock = clntsock
   def run(self):
      while 1:
         k = self.myclntsock.recv(1)
         if k == '': break
         # update v in an atomic manner
         srvr.vlock.acquire()
         srvr.v += k
         srvr.vlock.release()
         self.myclntsock.send(srvr.v)
      self.myclntsock.close()

#lstn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#port = int(sys.argv[1])  # server port number
#lstn.bind(('', port))
#lstn.listen(5)
nclnt = 20
mythreads = []  # list of all the threads

for i in range(nclnt):
   lstn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   lstn.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
   lstn.bind(('', 2000+i+1))
   lstn.listen(5)
   (clnt,ap) = lstn.accept()
   s = srvr(clnt)
   mythreads.append(s)
   s.start()

# shut down the server socket, since it's not needed anymore
#lstn.close()

# wait for all threads to finish
for s in mythreads:
   s.join()

print 'the final value of v is', srvr.v




More information about the Python-list mailing list