# L-37 MCS 275 Wed 14 Apr 2010 : pass_mtserver.py # Illustration of multithreaded server # to simulate login with password interaction. from socket import * from threading import * class Handler(Thread): """ Defines handler threads. """ def __init__(self,n,s,b,p): """ Name of handler is n, server socket is s, buffer size is b. Loing names and passwords are in the dictionary p. """ Thread.__init__(self,name=n) self.sv = s self.bf = b self.np = p def run(self): """ Accepts connection from a client and receives a login name. Checks if the name is a key in namespass and sends a reply to the client. If the name is a key, then the password sent by the client is checked and a reply is send back. """ n = self.getName() server = self.sv buffer = self.bf namespass = self.np client, client_address = server.accept() name = client.recv(buffer) print n + ' received \"' + name + '\"' if not namespass.has_key(name): print n + ' denies access' client.send('access denied') else: client.send('send password') pasw = client.recv(buffer) print n + ' received \"' + pasw + '\"' if namespass[name] == pasw: print n + ' grants access' client.send('access granted') else: print n + ' denies access' client.send('access denied') def connect(n,b): """ Connects a server to listen to n clients, buffer size is b. Returns the socket. """ hostname = '' # to use any address number = 11267 # number for the port buffer = b # size of the buffer server_address = (hostname, number) server = socket(AF_INET, SOCK_STREAM) server.bind(server_address) server.listen(n) return server def main(): """ Prompts for number of connections, starts the server and handler threads. """ n = input('give #clients : ') b = 80; server = connect(n,b) namespass = {'A':'1', 'B':'2'} print 'server is ready for %d clients' % n T = [] for i in range(0,n): T.append(Handler(str(i),server,b,namespass)) print 'server starts %d threads' % n for t in T: t.start() server.close() if __name__ == "__main__": main()