跳转到主要内容

为tornado提供的WSRPC WebSocket RPC

项目描述

https://travis-ci.org/mosquito/wsrpc.svg

浏览器和tornado之间的WebSocket远程过程调用。

功能

  • 从服务器端启动调用客户端函数。

  • 从客户端调用服务器方法。

  • 将任何异常从客户端传输到服务器端,反之亦然。

  • 前端库编写得很好,无需任何修改即可使用。

  • 完全异步的服务器端函数。

  • 基于线程的WebSocket处理程序,用于编写完全同步的代码(用于同步数据库驱动程序等)

  • 受保护的服务器端方法(以下划线开头,永远不会直接从客户端调用)

  • 异步连接协议。服务器或客户端可以以不可预测的顺序调用多个方法。

安装

通过pip安装

pip install wsrpc-tornado

如果您想安装,请安装ujson

pip install ujson

简单用法

添加后端

from time import time
## If you want write async tornado code import it
# from from wsrpc import WebSocketRoute, WebSocket, wsrpc_static
## else you should use thread-base handler
from wsrpc import WebSocketRoute, WebSocketThreaded as WebSocket, wsrpc_static

tornado.web.Application((
    # js static files will available as "/js/wsrpc.min.js".
    wsrpc_static(r'/js/(.*)'),
    # WebSocket handler. Client will connect here.
    (r"/ws/", WebSocket),
    # Serve other static files
    (r'/(.*)', tornado.web.StaticFileHandler, {
         'path': os.path.join(project_root, 'static'),
         'default_filename': 'index.html'
    }),
))

# This class should be call by client.
# Connection object will be have the instance of this class when will call route-alias.
class TestRoute(WebSocketRoute):
    # This method will be executed when client will call route-alias first time.
    def init(self, **kwargs):
        # the python __init__ must be return "self". This method might return anything.
        return kwargs

    def getEpoch(self):
        # this method named by camelCase because the client can call it.
        return time()

# stateful request
# this is the route alias TestRoute as "test1"
WebSocket.ROUTES['test1'] = TestRoute

# stateless request
WebSocket.ROUTES['test2'] = lambda *a, **kw: True

# initialize ThreadPool. Needed when using WebSocketThreaded.
WebSocket.init_pool()

添加前端

<script type="text/javascript" src="/js/q.min.js"></script>
<script type="text/javascript" src="/js/wsrpc.min.js"></script>
<script>
    var url = window.location.protocol==="https:"?"wss://":"ws://" + window.location.host + '/ws/';
    RPC = WSRPC(url, 5000);
    RPC.addRoute('test', function (data) { return "Test called"; });
    RPC.connect();

    RPC.call('test1.getEpoch').then(function (data) {
        console.log(data);
    }, function (error) {
        alert(error);
    }).done();

    RPC.call('test2').then(function (data) { console.log(data); }).done();
</script>

示例

示例运行在这里 demo

项目详情


由以下机构支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面