1import logging 2import socket 3 4_BUF_SIZE = 1024 5 6class FakePrinter(): 7 """A fake printer (server).""" 8 sock = 0 9 def __init__(self): 10 """Initialize fake printer""" 11 # Create a TCP/IP socket 12 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 13 # Bind the socket to the port 14 server_address = ('localhost', 9100) 15 self.sock.bind(server_address) 16 17 def start(self, log_file_path): 18 """Start the fake printer. 19 20 It listens on port 9100 and dump printing request 21 received to a temporary file. 22 23 Args: 24 @param log_file_path: the abs path of log file. 25 """ 26 # Listen for incoming printer request. 27 self.sock.listen(1) 28 logging.info('waiting for a printing request') 29 (connection, client_address) = self.sock.accept() 30 try: 31 logging.info('printing request from ' + str(client_address)) 32 logfile = open(log_file_path, 'w'); 33 while True: 34 data = connection.recv(_BUF_SIZE) 35 if not data: 36 logging.info('no more data from ' + str(client_address)) 37 break 38 logfile.write(data) 39 logfile.close(); 40 logging.info('printing request is dumped to ' + str(logfile)) 41 finally: 42 connection.close() 43