最近在了解 websocket,但是发现死活不能保持长连接,用 tornado 实现了一个 server:
# coding=utf8
from tornado.websocket import WebSocketHandler
from tornado.web import asynchronous, Application
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.gen import coroutine, sleep
class WSHandler(WebSocketHandler):
@asynchronous
def open(self, *args, **kwargs):
print '{0} connected'.format(self.request.remote_ip)
@coroutine
def on_message(self, message):
if message:
if message:
yield sleep(5)
self.write_message("it\'s is done")
def on_close(self):
print 'client is exit'
def main():
app = Application([(r'/', WSHandler)],
static_path='static')
server = HTTPServer(app)