python websocket server模块_WebSocket emulation - Python server

SockJS-tornado server

SockJS-tornado is a Python server side counterpart of SockJS-client browser library

running on top of Tornado framework.

Simplified echo SockJS server could look more or less like::

from tornado import web, ioloop

from sockjs.tornado import SockJSRouter, SockJSConnection

class EchoConnection(SockJSConnection):

def on_message(self, msg):

self.send(msg)

if __name__ == '__main__':

EchoRouter = SockJSRouter(EchoConnection, '/echo')

app = web.Application(EchoRouter.urls)

app.listen(9999)

ioloop.IOLoop.instance().start()

(Take look at examples for a complete version).

Subscribe to SockJS mailing list for discussions and support.

SockJS-tornado API

SockJS provides slightly different API than tornado.websocket. Main differences are:

Depending on transport, actual client connection might or might not be there. So, there is no _self.request_ and

other tornado.web.RequestHandler properties.

Changed open callback name to on_open to be more consistent with other callbacks.

Instead of write_message, all messages are sent using send method. Just in case, send in tornado.web.RequestHandler

sends raw data over the connection, without encoding it.

There is handy broadcast function, which accepts list (or iterator) of clients and message to send.

Settings

You can pass various settings to the SockJSRouter, in a dictionary:

MyRouter = SockJSRouter(MyConnection, '/my', dict(disabled_transports=['websocket']))

Deployment

sockjs-tornado properly works behind haproxy and it is recommended deployment approach.

Sample configuration file can be found here.

If your log is full of "WARNING: Connection closed by the client", pass no_keep_alive as True to HTTPServer constructor:

HTTPServer(app, no_keep_alive=True).listen(port)

or:

app.listen(port, no_keep_alive=True)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值