Skip to content

Instantly share code, notes, and snippets.

@aparrish
Created January 24, 2012 21:57
Show Gist options
  • Save aparrish/1672967 to your computer and use it in GitHub Desktop.
Save aparrish/1672967 to your computer and use it in GitHub Desktop.
simple python comet client
import email.utils # for rfc2822 formatted current timestamp
import requests
class CometClient(object):
def __init__(self, last_modified=None):
if last_modified is None:
self.last_modified = email.utils.formatdate()
else:
self.last_modified = last_modified
self.etag = 0
def listen(self, url):
while True:
self._get_request(url)
def _get_request(self, url):
try:
resp = requests.get(url, headers={
'If-None-Match': str(self.etag),
'If-Modified-Since': str(self.last_modified)})
self.last_modified = resp.headers['Last-Modified']
self.etag = resp.headers['Etag']
self.handle_response(resp.content)
except requests.exceptions.Timeout:
pass
def handle_response(self, response):
print response
if __name__ == '__main__':
import sys
comet = CometClient()
comet.listen(sys.argv[1])
@gonvaled
Copy link

I have tried to use this in different ways, but without success. I am connecting to a tornado comet server.

python simplecometclient.py localhost:8888/realtime/mygroup
requests.exceptions.InvalidSchema: Invalid scheme 'localhost'

python simplecometclient.py http://localhost:8888/realtime/mygroup
Can "Upgrade" only to "WebSocket".

python simplecometclient.py ws://localhost:8888/realtime/mygroup
requests.exceptions.InvalidSchema: Invalid scheme 'ws'

So how can I use this?

@aparrish
Copy link
Author

I guess I should have been more specific: this code doesn't work with websockets—it's for long-poll style Comet connections provided by, e.g., the nginx http push module (http://pushmodule.slact.net/). here are some good leads on Python websocket clients: http://stackoverflow.com/questions/3142705/is-there-a-websocket-client-implemented-for-python

@gonvaled
Copy link

Thanks for your prompt reply. Actually I am doing comet, not ws. I have tried the ws:// schema just because this is what the jquery part of the application is trying while establishing the conection to tornado. But I am pretty confident that the tornado server is doing comet, not web sockets (well, I am just reasonably confident). Could you provide an example of how you are using your script in your particular situation? Maybe some output would also be useful.

I have opened a StackOverflow question regarding this issue. You can see it here: http://stackoverflow.com/questions/11141618/simple-comet-client-in-python

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment