Skip to content

Commit

Permalink
add disconnect and better examples
Browse files Browse the repository at this point in the history
  • Loading branch information
wijowa committed Jul 9, 2020
1 parent 4e7e9db commit a46f95d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ for content in client.content_items():
```

If you want to get a more granular look at the connection status,
you can handle individual messages instead of just content items:
you can handle individual messages instead of just content items,
as well as disconnect the stream on command:

```python
from bztcp.client import Client, STATUS_STREAM
Expand All @@ -52,10 +53,15 @@ client = Client(username='USERNAME', key='APIKEY')
while True:
try:
msg = client.next_msg()

if msg.status == STATUS_STREAM:
print(f"Content item: {msg.data}")
else:
print(f"Status: {msg.status}")
except Exception as e:
print(f"Captured Exception: {e}")
except KeyboardInterrupt as ke:
print(f"Cancelled, disconnecting.")
client.disconnect()
except BzException as bze:
print(f"BZ Error: {bze}")
break
```
15 changes: 10 additions & 5 deletions bztcp/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ def __init__(self, username, key, host=None, port=None):
self._nextping = datetime.datetime.now() + ping_delta

# Connect and authenticate.
self.connected = False
self.connect()
self.authenticate()

Expand Down Expand Up @@ -137,6 +138,11 @@ def connect(self):
self._buf = b''
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock.connect((self._host, self._port))
self.connected = True

def disconnect(self):
self._sock.close()
self.connected = False

# Authenticates with the upstream server using credentials passed in.
def authenticate(self):
Expand Down Expand Up @@ -172,7 +178,7 @@ def ping(self):

# Returns the next message, sending pings at the ping interval.
def next_msg(self):
while True:
while self.connected:
ping_delta = datetime.timedelta(seconds=BZ_PING_INTERVAL)
now = datetime.datetime.now()

Expand All @@ -191,22 +197,21 @@ def next_msg(self):
try:
result = self.recv()
if result is not None and getattr(result, "data", "") != "":
#result2 = self.recv()
return result
else:
raise BzException(*ERR_NOT_CONNECTED)
except socket.timeout:
continue
raise BzException(*ERR_NOT_CONNECTED)

# Gets the next content item in the message stream.
def next_content(self):
while True:
while self.connected:
msg = self.next_msg()
if msg.status == STATUS_STREAM:
return msg

def content_items(self):
while True:
while self.connected:
yield self.next_content().data

0 comments on commit a46f95d

Please sign in to comment.