使用 Tornado 实现一个简单的 Websocket 服务器与客户端
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
不明觉厉~
页:
[1]