| 23 | |
| 24 | |
| 25 | class Connection: |
| 26 | def __init__(self, host, port): |
| 27 | self.host = host |
| 28 | self.port = port |
| 29 | self.socket = None |
| 30 | self.wrapper = None |
| 31 | self.lock = threading.Lock() |
| 32 | |
| 33 | def connect(self): |
| 34 | try: |
| 35 | self.socket = socket.socket() |
| 36 | # TODO: list the exceptions you want to catch |
| 37 | except socket.error: |
| 38 | if self.wrapper: |
| 39 | self.wrapper.error( |
| 40 | NO_VALID_ID, currentTimeMillis(), FAIL_CREATE_SOCK.code(), FAIL_CREATE_SOCK.msg() |
| 41 | ) |
| 42 | |
| 43 | try: |
| 44 | self.socket.connect((self.host, self.port)) |
| 45 | except socket.error: |
| 46 | if self.wrapper: |
| 47 | self.wrapper.error(NO_VALID_ID, currentTimeMillis(), CONNECT_FAIL.code(), CONNECT_FAIL.msg()) |
| 48 | |
| 49 | self.socket.settimeout(1) # non-blocking |
| 50 | |
| 51 | def disconnect(self): |
| 52 | self.lock.acquire() |
| 53 | try: |
| 54 | if self.socket is not None: |
| 55 | logger.debug("disconnecting") |
| 56 | self.socket.close() |
| 57 | self.socket = None |
| 58 | logger.debug("disconnected") |
| 59 | if self.wrapper: |
| 60 | self.wrapper.connectionClosed() |
| 61 | finally: |
| 62 | self.lock.release() |
| 63 | |
| 64 | def isConnected(self): |
| 65 | return self.socket is not None |
| 66 | |
| 67 | def sendMsg(self, msg): |
| 68 | logger.debug("acquiring lock") |
| 69 | self.lock.acquire() |
| 70 | logger.debug("acquired lock") |
| 71 | if not self.isConnected(): |
| 72 | logger.debug("sendMsg attempted while not connected, releasing lock") |
| 73 | self.lock.release() |
| 74 | return 0 |
| 75 | try: |
| 76 | nSent = self.socket.send(msg) |
| 77 | except socket.error: |
| 78 | logger.debug("exception from sendMsg %s", sys.exc_info()) |
| 79 | raise |
| 80 | finally: |
| 81 | logger.debug("releasing lock") |
| 82 | self.lock.release() |