如何使用Tornado将消息发送到Web套接字

时间:2017-09-20 19:45:09

标签: python django websocket tornado

您好我在后端使用TornadoDjango frammwork来处理前端的套接字消息。我对我的项目并不太熟悉,但我的项目中有一个文件,其中包含实现websocket.WebSocketHandlerweb.Application的类。这是此文件的一部分

class Application(web.Application):
    """
    Main Class for this application holding everything together.
    """
    def __init__(self):
        PROJECT_NAME = os.path.basename(os.getcwd())
        os.environ['DJANGO_SETTINGS_MODULE'] = PROJECT_NAME + 'tutorial/settings'

        # Handlers defining the url routing.
        handlers = [
            ('/room', SocketHandler),
            ('/room/([a-zA-Z0-9|=%]*)$', SocketHandler),
            ('/video_call', VideoCallSocketHandler),
            ('/video_call/([a-zA-Z0-9|=%]*)$', VideoCallSocketHandler),
        ]

在前端部分是一个功能:

var ws = new WebSocket('wss://domain.com:9003/video_call/' + conferenceId);

ws.onmessage = function (ev) {
    window.location.replace(redirectUrl);
};

我相信这个函数会从我们的移动应用程序中获取消息。

所以问题是我想从我的python视图发送消息到这个URL或'wss://domain.com:9003/video_call/' + conferenceId

例如:

def some_view_function(request, **kwargs):
    conference_id = request.GET.data['conferenceId']
    ...
    if something:
       send message to wss://domain.com:9003/video_call/' + conference_id

我该怎么做?

1 个答案:

答案 0 :(得分:0)

龙卷风包装django代码怎么样?

def main():
    os.environ['DJANGO_SETTINGS_MODULE'] = 'docs.settings'
    application = get_wsgi_application()
    container = tornado.wsgi.WSGIContainer(application)

    tornado_app = tornado.web.Application(
       [('.*', tornado.web.FallbackHandler, dict(fallback=container))],        
    )

    server = tornado.httpserver.HTTPServer(tornado_app)
    server.bind(8888)
    server.start(0)
    tornado.ioloop.IOLoop.instance().start()

django和龙卷风之间的沟通我建议通过队列进行沟通,比如Redis。

def some_view_function(request, **kwargs):
    conference_id = request.GET.data['conferenceId']
    ...
    if something:
       send_to_queue()

龙卷风侧队列侦听器。