# # Create a number of "publishers" on the localhost, all # using a different socket. Each publisher will publish # periodic messages containing json formatted data that # can be consumed by the client for display, mimicing # data from many different computers. # import zmq import json import time import threading import random Nservers = 10 starting_port = 5555 # Each server is represented by an object of this class class HDserver: def __init__(self, port): self.port = port self.host = 'fake_host%02d' % port # Set up publisher self.context = zmq.Context() self.socket = self.context.socket(zmq.PUB) self.socket.bind("tcp://*:%d" % port) # Initialize with some random values self.datarate_mean = random.uniform( 100.0, 500.0 ) # MB/s self.datarate_sigma = random.uniform( 10.0, 50.0 ) # MB/s self.Nfiles = random.randint( 5, 100 ) # Run server loop in separate thread self.thread = threading.Thread(target=self.Loop) self.done = False self.thread.start() # This is run in a separate thread publishing messages periodically # until told to stop via the End() proc being called def Loop(self): print('Starting thread for port %d' % self.port) time.sleep(random.randrange(10)) # sleep random amount of time to put servers out of sync # Loop continuously while not self.done: print('-- port %d:' % self.port) # Create dictionary of values to send myinfo = {} myinfo['host'] = self.host myinfo['avg5min'] = random.normalvariate( self.datarate_mean, self.datarate_sigma ) myinfo['Nfiles'] = self.Nfiles = self.Nfiles + random.randrange(10) # Send entire dictionary as json file myjson = json.dumps( myinfo ) self.socket.send_string(myjson) time.sleep(3) # Stop the server thread def End(self): print('Ending thread for port %d ...' % self.port) self.done = True threading.Thread(target=lambda a: a.thread.join(), args=(self)) # join in separate thread so we can return immediately print( 'Port %d done.' % self.port ) #----------------------------------------------------------------------------------- # main # Create N servers servers =[] for i in range(0,Nservers): port = starting_port + i server = HDserver(port) servers.append( server ) # Loop continuously. Put it in a try-except block so keyboard interrupts are caught cleanly try: while True: time.sleep(1) except: pass print('\nShutting down servers ....') for s in servers: s.End() print('\nFinished.')