1
2
3
4 """
5 Simple clients (built on synchronous sockets).
6 """
7
8 import socket
9 from commons.log import *
10
12 """
13 A simple wrapper around a socket which re-connects if necessary.
14 """
15 - def __init__( self, host, port, init_msg ):
16 """
17 @param host: Host to connect to.
18 @type host: str
19 @param host: Port to connect to.
20 @param port: int
21 @param init_msg: The message to be sent on reconnection.
22 @param init_msg: str
23 """
24 self.addr = ( host, port )
25 self.init_msg = init_msg
26 self.socket = None
27
28 - def send( self, msg ):
29 """
30 Whenever a connection is lost, it tries to resend.
31 If a connection cannot be established, the message is discarded.
32 """
33 try:
34 if self.socket is None:
35 debug( 'PersistentSender', '(re)connecting to', self.addr )
36 self.socket = socket.socket()
37 self.socket.connect( self.addr )
38 self.socket.send( self.init_msg )
39 self.socket.send( msg )
40 except socket.error, ex:
41 debug( 'PersistentSender', 'no connection:', ex )
42 self.socket = None
43
45 """
46 Closes the socket (if it's connected).
47 """
48 if self.socket is not None:
49 self.socket.close()
50