Fixed bug which caused PyBLIP to stop sending responses while the connection was closing.
     6 Created by Jens Alfke on 2008-06-04.
 
     7 This source file is test/example code, and is in the public domain.
 
    10 from BLIP import Connection, OutgoingRequest, kOpening
 
    13 from cStringIO import StringIO
 
    14 from datetime import datetime
 
    21 kNBatchedMessages = 4 # send only 40 requests total
 
    25     return random.randint(0,1) == 1
 
    28 class BLIPConnectionTest(unittest.TestCase):
 
    31         self.connection = Connection( ('localhost',46353) )
 
    32         self.nRepliesPending = 0
 
    34     def sendRequest(self):
 
    35         size = random.randint(0,32767)
 
    37         for i in xrange(0,size):
 
    38             io.write( chr(i % 256) )
 
    42         req = OutgoingRequest(self.connection, body,{'Content-Type': 'application/octet-stream',
 
    43                                                      'User-Agent':  'PyBLIP',
 
    44                                                      'Date': datetime.now(),
 
    46         req.compressed = randbool()
 
    47         req.urgent     = (random.randint(0,kUrgentEvery-1)==0)
 
    48         req.response.onComplete = self.gotResponse
 
    51     def gotResponse(self, response):
 
    52         self.nRepliesPending -= 1
 
    53         logging.info("Got response!: %s (%i pending)",response,self.nRepliesPending)
 
    54         request = response.request
 
    55         assert response.body == request.body
 
    60         while nIterations < 10:
 
    61             asyncore.loop(timeout=kSendInterval,count=1)
 
    64             if self.connection.status!=kOpening and (not lastReqTime or (now-lastReqTime).microseconds >= kSendInterval*1.0e6):
 
    66                 for i in xrange(0,kNBatchedMessages):
 
    67                     if not self.sendRequest():
 
    68                         logging.warn("Couldn't send request (connection is probably closed)")
 
    70                     self.nRepliesPending += 1
 
    74         self.connection.close()
 
    75         asyncore.loop() # got to give it time to negotiate close; this call should exit eventually
 
    77 if __name__ == '__main__':
 
    78     logging.basicConfig(level=logging.INFO)