Created
July 21, 2012 06:45
-
-
Save ibigbug/3154896 to your computer and use it in GitHub Desktop.
Tornado count online number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding:utf8 -*- | |
import os | |
import tornado.web | |
from tornado.httpserver import HTTPServer | |
from tornado.ioloop import IOLoop | |
import uuid | |
class MainHandler(tornado.web.RequestHandler): | |
def get(self): | |
self.render('index.html', name=uuid.uuid4()) | |
class CountHandler(tornado.web.RequestHandler): | |
users = set() | |
def get(self): | |
""" | |
user offline | |
""" | |
user = self.get_argument('name') | |
CountHandler.users.remove(user) | |
self._on_finish() | |
def post(self): | |
""" | |
user online | |
""" | |
self.user = user = self.get_argument('name') | |
CountHandler.users.add(user) | |
self._on_finish() | |
def _on_finish(self): | |
if self.request.connection.stream.closed(): | |
return | |
print len(CountHandler.users) | |
self.finish(u'当前在线人数' + str(len(CountHandler.users))) | |
def main(): | |
settings = { | |
'template_path': os.path.join(os.path.dirname(__file__), 'templates'), | |
'static_path': os.path.join(os.path.dirname(__file__), 'static'), | |
'debug': True, | |
} | |
app = tornado.web.Application([ | |
(r'/', MainHandler), | |
('/count', CountHandler), | |
], **settings) | |
server = HTTPServer(app) | |
server.listen(8000) | |
IOLoop.instance().start() | |
if __name__ == '__main__': | |
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE HTML> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Online Number Demo</title> | |
</head> | |
<body> | |
<span class="count"></span> | |
<script src="{{ static_url('jquery.js') }}" type="text/javascript"></script> | |
<script type="text/javascript"> | |
(function test(){ | |
window.setTimeout(function(){ | |
$.ajax({ | |
url: '/count', | |
type: 'POST', | |
data: { name: '{{ name }}' }, | |
success: function(data){ | |
$('.count').html(data); | |
} | |
}); | |
test(); | |
}, 5000); | |
})(); | |
$(window).unload(function(){ | |
$.ajax({ | |
async: false, | |
url: '/count?name={{ name }}', | |
type: 'GET', | |
success: function(){ | |
} | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment