# E-2 MCS 275 Fri 16 Apr 2010 : ex2q3.py # Write code for a server that keeps a dictionary of its connecting clients. # The key of this dictionary is the address of the client. # The corresponding value equals the first number the client sends # to the server. # After sending first a number to the server, every client is expected # to send exactly as many messages to the server as the value # of the first number. Every message contains exactly one character. # After all messages have been sent, the server closes the connection # to the client. # Set up the server to handle an indefinite number of clients indefinitely. from SocketServer import StreamRequestHandler, TCPServer port = 12091 D = {}; S = {} class OurServer(StreamRequestHandler): def handle(self): """ Updates dictionary with address of client and then collects data in a string. """ print "connected at", self.client_address data = self.rfile.read(10) key = str(self.client_address) print 'read \"' + data + '\" from client' D[key] = int(data) print 'handling %d messages from client %s' % (D[key],key) print 'dictionary : ' + str(D) for i in range(0,D[key]): data = self.rfile.read(1) print 'read \"' + data + '\" from ' + key if not S.has_key(key): S[key] = data else: S[key] = S[key] + data self.rfile.close() print 'received ' + S[key] + ' from ' + key ss = TCPServer(('',port),OurServer) print 'server is listening to', port try: print 'press ctrl c to stop server' ss.serve_forever() except KeyboardInterrupt: print ' ctrl c pressed, closing server' ss.socket.close()