<s> """<STR_LIT>""" <EOL> import logging , time <EOL> from tornadio import proto , periodic <EOL> class SocketConnection ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , protocol , io_loop , heartbeat_interval ) : <EOL> """<STR_LIT>""" <EOL> self . _protocol = protocol <EOL> self . _io_loop = io_loop <EOL> self . _heartbeat_timer = None <EOL> self . _heartbeats = <NUM_LIT:0> <EOL> self . _missed_heartbeats = <NUM_LIT:0> <EOL> self . _heartbeat_delay = None <EOL> self . _heartbeat_interval = heartbeat_interval * <NUM_LIT:1000> <EOL> self . is_closed = False <EOL> def on_open ( self , * args , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> pass <EOL> def on_message ( self , message ) : <EOL> """<STR_LIT>""" <EOL> raise NotImplementedError ( ) <EOL> def on_close ( self ) : <EOL> """<STR_LIT>""" <EOL> pass <EOL> def send ( self , message ) : <EOL> """<STR_LIT>""" <EOL> self . _protocol . send ( message ) <EOL> def close ( self ) : <EOL> """<STR_LIT>""" <EOL> self . stop_heartbeat ( ) <EOL> self . _protocol . close ( ) <EOL> def raw_message ( self , message ) : <EOL> """<STR_LIT>""" <EOL> for msg in proto . decode ( message ) : <EOL> if msg [ <NUM_LIT:0> ] == proto . FRAME or msg [ <NUM_LIT:0> ] == proto . JSON : <EOL> self . on_message ( msg [ <NUM_LIT:1> ] ) <EOL> elif msg [ <NUM_LIT:0> ] == proto . HEARTBEAT : <EOL> logging . debug ( '<STR_LIT>' ) <EOL> self . _missed_heartbeats -= <NUM_LIT:1> <EOL> def reset_heartbeat ( self , interval = None ) : <EOL> """<STR_LIT>""" <EOL> self . stop_heartbeat ( ) <EOL> if interval is None : <EOL> interval = self . _heartbeat_interval <EOL> self . _heartbeat_timer = periodic . Callback ( self . _heartbeat , <EOL> interval , <EOL> self . _io_loop ) <EOL> self . _heartbeat_timer . start ( ) <EOL> def stop_heartbeat ( self ) : <EOL> """<STR_LIT>""" <EOL> if self . _heartbeat_timer is not None : <EOL> self . _heartbeat_timer . stop ( ) <EOL> self . _heartbeat_timer = None <EOL> def delay_heartbeat ( self ) : <EOL> """<STR_LIT>""" <EOL> if self . _heartbeat_timer is not None : <EOL> self . _heartbeat_delay = self . _heartbeat_timer . calculate_next_run ( ) <EOL> def send_heartbeat ( self ) : <EOL> """<STR_LIT>""" <EOL> self . _heartbeats += <NUM_LIT:1> <EOL> self . _missed_heartbeats += <NUM_LIT:1> <EOL> self . send ( '<STR_LIT>' % self . _heartbeats ) <EOL> def _heartbeat ( self ) : <EOL> """<STR_LIT>""" <EOL> if ( self . _heartbeat_delay is not None <EOL> and time . time ( ) < self . _heartbeat_delay ) : <EOL> delay = self . _heartbeat_delay <EOL> self . _heartbeat_delay = None <EOL> return delay <EOL> logging . debug ( '<STR_LIT>' ) <EOL> if self . _missed_heartbeats > <NUM_LIT:5> : <EOL> logging . debug ( '<STR_LIT>' ) <EOL> self . close ( ) <EOL> else : <EOL> self . send_heartbeat ( ) </s>
