tornado websocket 客户端与服务器端示例

最近在网上找了些websocket的资料看了下,node和tornado等等本身已经实现了websocket的封装,所以使用起来会比较简单,php如果想要写websocket还需要自己跑一整套流程,比较麻烦。

tornado websocket 客户端与服务器端示例

根据网上的资料写了一个简单的 websocket 的demo,果真炫酷掉渣天,我是用tornado,网上多是实现实时聊天室的例子,想要实现点对点的聊天功能还需要在send函数那里加条件,目测是根据浏览器用户的id去判断的。代码如下:

服务端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/python
#coding:utf-8
import os.path

import tornado.httpserver
import tornado.web
import tornado.ioloop
import tornado.options
import tornado.httpclient
import tornado.websocket

import json
class IndexHandler(tornado.web.RequestHandler):
  def get(self):
    self.render("index.html")

class SocketHandler(tornado.websocket.WebSocketHandler):
  """docstring for SocketHandler"""
  clients = set()

  @staticmethod
  def send_to_all(message):
      for c in SocketHandler.clients:
          c.write_message(json.dumps(message))

  def open(self):
      self.write_message(json.dumps({
          'type': 'sys',
          'message': 'Welcome to WebSocket',
      }))
      SocketHandler.send_to_all({
          'type': 'sys',
          'message': str(id(self)) + ' has joined',
      })
      SocketHandler.clients.add(self)

  def on_close(self):
      SocketHandler.clients.remove(self)
      SocketHandler.send_to_all({
          'type': 'sys',
          'message': str(id(self)) + ' has left',
      })

  def on_message(self, message):
    SocketHandler.send_to_all({
  'type': 'user',
  'id': id(self),
  'message': message,
        })
    
##MAIN
if __name__ == '__main__':
  app = tornado.web.Application(
    handlers=[
      (r"/", IndexHandler),
      (r"/chat", SocketHandler)
    ],
    debug = True,
    template_path = os.path.join(os.path.dirname(__file__), "templates"),
        static_path = os.path.join(os.path.dirname(__file__), "static")
  )
  app.listen(8000)
  tornado.ioloop.IOLoop.instance().start()

客户端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<html>
<head>
<script type="text/javascript">
var ws = new WebSocket("ws://localhost:8000/chat");
ws.onmessage = function(event) {
  console.log(event);
}
function send() {
  ws.send(document.getElementById('chat').value );
}
</script>
</head>

<body>
  <div>
    hello
    <input id="chat">
    <button  onclick="send()">send</button>
  </div>	
</body>
</html>

本文网址: https://pylist.com/topic/58.html 转摘请注明来源

Suggested Topics

SAE+python+Tornado+pyTenjin 的完整示例

python 简单易懂,Tornado 高效易学,pyTenjin 轻巧快速,SAE 安全稳定使用门槛低。现在把他们结合在一起做了一个可运行在SAE 上的完整示例。...

Tornado 搭建基于 WebSocket 的聊天服务

这年头 Python web 框架是有点泛滥了. 下面要介绍的是 facebook 的开源框架 tornado. 这东西比较简单, 而且自带 WebSocket 支持, 可以用它做个简单的聊天室. ...

Tornado 构建一个 Comet 应用

Comet -- 基于 HTTP 长连接、无须在浏览器端安装插件的“服务器推”技术为“Comet”,这里介绍用Tornado 构建一个 Comet 应用的经验。...

Leave a Comment