<s> import os <EOL> import time <EOL> from telnetlib import Telnet <EOL> from django . core . cache import cache <EOL> class TelnetClient ( ) : <EOL> def __init__ ( self , port , password , server_id ) : <EOL> self . terminate = False <EOL> self . server_id = server_id <EOL> self . tn = Telnet ( '<STR_LIT:localhost>' , port ) <EOL> self . tn . read_until ( '<STR_LIT>' . format ( os . linesep ) ) <EOL> self . tn . write ( password + os . linesep ) <EOL> self . start_time = time . time ( ) <EOL> self . run ( ) <EOL> def read ( self ) : <EOL> try : <EOL> return self . tn . read_eager ( ) <EOL> except : <EOL> self . terminate = True <EOL> return '<STR_LIT>' <EOL> def write ( self , line ) : <EOL> try : <EOL> self . tn . write ( line . encode ( '<STR_LIT>' ) + os . linesep ) <EOL> except : <EOL> self . terminate = True <EOL> def send_back ( self , lines_to_send ) : <EOL> key = '<STR_LIT>' . format ( self . server_id ) <EOL> lines = cache . get ( key , [ ] ) <EOL> lines . extend ( lines_to_send ) <EOL> cache . set ( key , lines ) <EOL> def get_lines_from_cache ( self ) : <EOL> key = '<STR_LIT>' . format ( self . server_id ) <EOL> lines = cache . get ( key , [ ] ) <EOL> cache . delete ( key ) <EOL> return lines <EOL> def ping ( self ) : <EOL> pingtime = cache . get ( '<STR_LIT>' . format ( self . server_id ) ) <EOL> if not pingtime or time . time ( ) - pingtime > <NUM_LIT:3> : <EOL> self . terminate = True <EOL> def run ( self ) : <EOL> received_data = '<STR_LIT>' <EOL> while True : <EOL> self . ping ( ) <EOL> if self . terminate : <EOL> break <EOL> received_data += self . read ( ) <EOL> lines = received_data . split ( os . linesep ) <EOL> received_data = lines . pop ( ) <EOL> if lines : <EOL> self . send_back ( lines ) <EOL> for line in self . get_lines_from_cache ( ) : <EOL> self . write ( line ) <EOL> time . sleep ( <NUM_LIT> ) </s>
