# L-29 MCS 275 Fri 19 Mar 2010 : scripts_server.py # Database server to scripts in OurPyFiles database. # Sends number of scripts in the table 'scripts' # in the MySQL database 'OurPyFiles' to the client. # Requirements for a successful run: # (1) MySQL must be started (sudo mysqld_safe); and # (2) run this script as sudo python scripts_count.py. import MySQLdb from socket import * hostname = '' # use any address number = 11267 # number for the port buffer = 80 # size of the buffer def connect(): """ Returns client and server socket to communicate with one client. """ server_address = (hostname, number) server = socket(AF_INET, SOCK_STREAM) server.bind(server_address) server.listen(1) print 'server waits for connection' client, client_address = server.accept() print 'server accepted connection from ',\ client_address return client, server def count(): """ Returns the number of scripts. """ db = MySQLdb.connect(db='OurPyFiles') cr = db.cursor() q = 'select count(*) from scripts' cr.execute(q) r = cr.fetchone() n = int(r[0]) return n def main(): """ Accepts connection and sends #scripts. """ client, server = connect() print 'server connects to database' nb = count() print 'server sends #scripts to client' data = str(nb) client.send(data) print 'count sent, closing off' server.close() main()