<s> from __future__ import absolute_import <EOL> import socket <EOL> import struct <EOL> from nsq import protocol <EOL> class SyncConn ( object ) : <EOL> def __init__ ( self , timeout = <NUM_LIT:1.0> ) : <EOL> self . buffer = '<STR_LIT>' <EOL> self . timeout = timeout <EOL> self . s = None <EOL> def connect ( self , host , port ) : <EOL> assert isinstance ( host , ( str , unicode ) ) <EOL> assert isinstance ( port , int ) <EOL> self . s = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) <EOL> self . s . settimeout ( self . timeout ) <EOL> self . s . connect ( ( host , port ) ) <EOL> self . s . send ( protocol . MAGIC_V2 ) <EOL> def _readn ( self , size ) : <EOL> while True : <EOL> if len ( self . buffer ) >= size : <EOL> break <EOL> packet = self . s . recv ( <NUM_LIT> ) <EOL> if not packet : <EOL> raise Exception ( '<STR_LIT>' % size ) <EOL> self . buffer += packet <EOL> data = self . buffer [ : size ] <EOL> self . buffer = self . buffer [ size : ] <EOL> return data <EOL> def read_response ( self ) : <EOL> size = struct . unpack ( '<STR_LIT>' , self . _readn ( <NUM_LIT:4> ) ) [ <NUM_LIT:0> ] <EOL> return self . _readn ( size ) <EOL> def send ( self , data ) : <EOL> self . s . send ( data ) </s>
