|
Tornado 是 Python 的一个 Web 服务器框架,它是非阻塞式的,非常适合用来做长连接服务器,http://www.tornadoweb.cn/。
具体文档请看链接,直接上代码了:
- # Websocket 服务端
- import tornado
- import tornado.websocket
- class EchoWebSocket(tornado.websocket.WebSocketHandler):
- def open(self):
- print("WebSocket opened")
- def on_message(self, message):
- print message
- self.write_message(u"You said: " + message)
- def on_close(self):
- print("WebSocket closed")
- if __name__=='__main__':
- app = tornado.web.Application([
- (r'/', EchoWebSocket),
- ])
- app.listen(8000)
- tornado.ioloop.IOLoop.current().start()
复制代码- # Websocket 客户端
- import tornado
- from tornado.websocket import websocket_connect
- class WSClient(object):
- def __init__(self, url):
- self.url = url
- self.ioloop = tornado.ioloop.IOLoop.current()
- def start(self):
- websocket_connect(
- self.url,
- self.ioloop,
- callback=self.on_connected,
- on_message_callback=self.on_message)
- self.ioloop.start()
- def on_connected(self, f):
- try:
- conn = f.result()
- conn.write_message("hello")
- except Exception, e:
- print str(e)
- self.ioloop.stop()
- def on_message(self, msg):
- print msg
- if msg.endswith("hello"):
- self.ioloop.stop()
- if __name__=='__main__':
- wsc = WSClient('ws://localhost:8000')
复制代码
运行效果:
- # server
- $ python websocket.py
- WebSocket opened
- hello
- WebSocket closed
复制代码- # client
- $ python ws_client.py
- You said: hello
复制代码
|
|