【问题标题】:Send message from server to client after received notification (Tornado+websockets)收到通知后从服务器向客户端发送消息(Tornado+websockets)
【发布时间】:2014-01-09 14:35:34
【问题描述】:

我最近开始学习 websockets,我决定尝试学习和使用 Python 的 framweork Tornado 来创建我的简单测试项目(没什么特别的,只是可以帮助我了解 Tornado 和 websockets 的基本项目) .

所以,这是我的想法(工作流程):

1)我从其他应用程序向我的服务器发送 http post 请求(例如,有关某人姓名和电子邮件的信息)

2) 我将收到的数据保存到我的 postgresql 数据库并通知侦听器(发布/订阅)新数据已添加到数据库中

3) 服务器收到通知后应该向客户端发送消息(write_message 方法)

这是我现在的代码

simple_server.py

import tornado.httpserver
import tornado.ioloop
import tornado.options 
import tornado.web
import tornado.websocket
import psycopg2
import psycopg2.extensions
import os
from tornado.options import define, options

define("port", default=8000, help="run on the given port", type=int)

io_loop = tornado.ioloop.IOLoop.instance()

connection = psycopg2.connect('dbname=mydb user=myusername password=mypassword')
connection.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html')

class ReceivedDataHandler(tornado.web.RequestHandler):  
    def post(self):     
        cursor = connection.cursor()

        name=self.get_argument('name', 'No name info received')
        email = self.get_argument('email', 'No email info received')
        self.write("New person with name %s and email %s" %(name, email))

        cursor.execute("INSERT INTO mydata VALUES (%s, %s)" %(name, email))
        cursor.execute("NOTIFY test_channel;")

class EchoHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        self.write_message('connected!')
    def on_message(self, message):
        self.write_message("Received info about new person: "+message)
    def on_close(self):
        print 'connection closed'

def listen():    
    cursor = connection.cursor()
    cursor.execute("LISTEN test_channel;") 

def receive(fd, events):
    """Receive a notify message from channel I listen."""
    state = connection.poll()
    if state == psycopg2.extensions.POLL_OK:
        if connection.notifies:
            notify = connection.notifies.pop()
            print "New notify message"
io_loop.add_handler(connection.fileno(), receive, io_loop.READ)

if __name__=="__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(
        handlers=[
            (r'/', IndexHandler),
            (r'/person-info', ReceivedDataHandler),
            (r'/websocket', EchoHandler)
        ],
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        static_path=os.path.join(os.path.dirname(__file__), "static"),
        debug=True
    )
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    listen()
    io_loop.start()

当我测试发送帖子请求(通过 Postman REST 客户端)到定义的 url 时,一切正常。数据确实保存到我的数据库中,它确实通知侦听器有新通知,但我只是不知道之后如何将该消息发送给客户端。 如果我能做到这一点,那么它将在浏览器中显示该消息,这就是我这次要做的全部。

所以,我想要做的实际上是在收到有关数据库中新条目的通知后调用 write_message 函数(而不仅仅是打印“新通知消息”),但我只是不知道如何在 Tornado 中执行此操作。 我相信它实际上应该很容易,但由于我显然缺乏 Tornado(和异步编程)的经验,所以我有点卡住了。

感谢您的帮助

【问题讨论】:

    标签: python websocket real-time tornado publish-subscribe


    【解决方案1】:

    最终我找到了解决这个问题的方法。 我刚刚添加了全局变量,在其中添加了所有连接的客户端,然后在收到通知时向每个连接的客户端发送消息。 (这对我来说没关系,因为我实际上想向所有连接的客户端发送消息)

    这就是现在的样子

    simple_server.py

    import tornado.httpserver
    import tornado.ioloop
    import tornado.options 
    import tornado.web
    import tornado.websocket
    import psycopg2
    import psycopg2.extensions
    import os
    from tornado.options import define, options
    
    define("port", default=8000, help="run on the given port", type=int)
    
    io_loop = tornado.ioloop.IOLoop.instance()
    
    connection = psycopg2.connect('dbname=mydb user=myusername password=mypassword')
    connection.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
    
    # This is a global variable to store all connected clients
    websockets = []
    
    class IndexHandler(tornado.web.RequestHandler):
        def get(self):
            self.render('index.html')
    
    class ReceivedDataHandler(tornado.web.RequestHandler):  
        def post(self):     
            cursor = connection.cursor()
    
            name=self.get_argument('name', 'No name info received')
            email = self.get_argument('email', 'No email info received')
            self.write("New person with name %s and email %s" %(name, email))
    
            cursor.execute("INSERT INTO mydata VALUES (%s, %s)" %(name, email))
            cursor.execute("NOTIFY test_channel;")
    
    class EchoHandler(tornado.websocket.WebSocketHandler):
        def open(self):
            self.write_message('connected!')
        def on_message(self, message):
            self.write_message("Received info about new person: "+message)
        def on_close(self):
            print 'connection closed'
    
    def listen():    
        cursor = connection.cursor()
        cursor.execute("LISTEN test_channel;") 
    
    def receive(fd, events):
        """Receive a notify message from channel I listen."""
        state = connection.poll()
        if state == psycopg2.extensions.POLL_OK:
            if connection.notifies:
                notify = connection.notifies.pop()
                for ws in websockets:
                       ws.write_message("my message")
    io_loop.add_handler(connection.fileno(), receive, io_loop.WRITE)
    
    if __name__=="__main__":
        tornado.options.parse_command_line()
        app = tornado.web.Application(
            handlers=[
                (r'/', IndexHandler),
                (r'/person-info', ReceivedDataHandler),
                (r'/websocket', EchoHandler)
            ],
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            debug=True
        )
        http_server = tornado.httpserver.HTTPServer(app)
        http_server.listen(options.port)
        listen()
        io_loop.start()
    

    【讨论】:

    • 但是如果您将拥有多个 Tornado 服务器怎么办?
    • @madzohan - 您可以使用 Redis 存储连接的客户端和服务器的键/值对。
    猜你喜欢
    • 2020-09-06
    • 2013-08-17
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多