收藏官网首页
查看: 9197|回复: 1

使用 Tornado 实现一个简单的 Websocket 服务器与客户端

7

主题

38

帖子

283

积分

中级会员

Rank: 3Rank: 3

积分
283
跳转到指定楼层
楼主
发表于 2015-8-28 11:55:45 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
注册成为机智云开发者,手机加虚拟设备快速开发
Tornado 是 Python 的一个 Web 服务器框架,它是非阻塞式的,非常适合用来做长连接服务器,http://www.tornadoweb.cn/

具体文档请看链接,直接上代码了:

  1. # Websocket 服务端
  2. import tornado
  3. import tornado.websocket

  4. class EchoWebSocket(tornado.websocket.WebSocketHandler):

  5.     def open(self):
  6.         print("WebSocket opened")

  7.     def on_message(self, message):
  8.         print message
  9.         self.write_message(u"You said: " + message)

  10.     def on_close(self):
  11.         print("WebSocket closed")


  12. if __name__=='__main__':
  13.     app = tornado.web.Application([
  14.         (r'/', EchoWebSocket),
  15.     ])
  16.     app.listen(8000)
  17.     tornado.ioloop.IOLoop.current().start()
复制代码
  1. # Websocket 客户端
  2. import tornado
  3. from tornado.websocket import websocket_connect


  4. class WSClient(object):

  5.     def __init__(self, url):
  6.         self.url = url
  7.         self.ioloop = tornado.ioloop.IOLoop.current()

  8.     def start(self):
  9.         websocket_connect(
  10.             self.url,
  11.             self.ioloop,
  12.             callback=self.on_connected,
  13.             on_message_callback=self.on_message)
  14.         self.ioloop.start()

  15.     def on_connected(self, f):
  16.         try:
  17.             conn = f.result()
  18.             conn.write_message("hello")
  19.         except Exception, e:
  20.             print str(e)
  21.             self.ioloop.stop()

  22.     def on_message(self, msg):
  23.         print msg
  24.         if msg.endswith("hello"):
  25.             self.ioloop.stop()


  26. if __name__=='__main__':
  27.     wsc = WSClient('ws://localhost:8000')
复制代码

运行效果:
  1. # server
  2. $ python websocket.py
  3. WebSocket opened
  4. hello
  5. WebSocket closed
复制代码
  1. # client
  2. $ python ws_client.py
  3. You said: hello
复制代码


您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

加入Q群 返回顶部

版权与免责声明 © 2006-2024 Gizwits IoT Technology Co., Ltd. ( 粤ICP备11090211号 )

快速回复 返回顶部 返回列表