【问题标题】:Tornado-eventsource server not getting messagesTornado-eventsource 服务器没有收到消息
【发布时间】:2020-12-22 20:53:43
【问题描述】:

我正在处理 Rabbitmq 和服务器为此发送的事件我使用该代码中的 tornado-eventsource (https://github.com/guilhermef/tornado-eventsource/tree/master/tornado_eventsource) 我尝试连接 EventSource。当我的服务器接收到消息时,它会自动将其发送给客户端,但它会给出此错误消息,并且服务器不会监视消息以发送 但我猜是由于我使用 python3 时版本发生了变化,我得到了一个错误。

文件“C:\Users\Admin\AppData\Local\Programs\Python\Python37\lib\site-packages\tornado_eventsource\handler.py”,第 71 行,在 write_message 如果 isinstance(msg, str) 或 isinstance(msg, unicode): NameError: name 'unicode' is not defined

请指导我。

这里是服务器端代码:

import _thread
import asyncio
import time
import os
import tornado.ioloop
import tornado.web
from DateTime import DateTime
import pika
from tornado.web import Application, RequestHandler
from threading import Thread
import logging
import six
#from tornadose.handlers 
import tornado_eventsource.handler
from tornado_eventsource.handler import EventSourceHandler


logging.basicConfig(level=logging.INFO)
# web socket clients connected.
clients = []

connection = pika.BlockingConnection()
logging.info('Connected:localhost')
channel = connection.channel()
print("Connection Time: ", time.time()*1000)
print("Connection Time: ", DateTime())
def get_connection():
    credentials = pika.PlainCredentials('guest', 'guest')
    conn = pika.BlockingConnection(pika.ConnectionParameters(host="localhost", port=5672,
                                                             virtual_host="/",
                                                             credentials=credentials))
    return conn

def callback(ch, method, properties, body):
    print(" [x] Received %r", fetch_DateTime(), ':', body)
    time.sleep(body.count(b'.'))
    #print(fetch_DateTime())
    for itm in clients:
        itm.write_message(body)


def start_consumers():
    asyncio.set_event_loop(asyncio.new_event_loop())
    channel = get_connection().channel()
    channel.queue_declare(queue="my_queue")
    channel.basic_consume(
        queue="my_queue",
        on_message_callback=callback,
        auto_ack=True)

    channel.start_consuming()

def fetch_DateTime():
    time_milliseconds = time.time() * 1000
    return(time_milliseconds)


def disconnect_to_rabbitmq():
    channel.stop_consuming()
    connection.close()
    logging.info('Disconnected from Rabbitmq')


class EventHandler(tornado_eventsource.handler.EventSourceHandler):

    def open(self):
        logging.info('Server-Sent Events opened')
        clients.append(self)
    
    

    def on_close(self):
        logging.info('Server-Sent Events closed')
        clients.remove(self)


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("SSE_client.html")


def make_app():
    return tornado.web.Application([
        (r'/', EventHandler,),
        (r"/", MainHandler),
    ])


class WebServer(tornado.web.Application):

    def __init__(self):
        handlers = [ (r'/', EventHandler,),
                     (r"/", MainHandler), ]
        settings = {'debug': True}
        super().__init__(handlers, **settings)

    def run(self, port=8888):
        self.listen(port)
        tornado.ioloop.IOLoop.instance().start()


class TestHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("test success")


ws = WebServer()


def start_server():
    asyncio.set_event_loop(asyncio.new_event_loop())
    ws.run()


if __name__ == "__main__":

    logging.info('Starting thread Tornado')
    threadC = Thread(target=start_consumers)
    threadC.start()

    from threading import Thread

    t = Thread(target=start_s

    erver, args=())
        t.daemon = True
        t.start()
    
        t.join()
        try:
            input("Server ready. Press enter to stop\n")
        except SyntaxError:
            pass
        try:
            logging.info('Disconnecting from RabbitMQ..')
            disconnect_to_rabbitmq()
        except Exception:
            pass
        stopTornado();
    
        logging.info('See you...')

【问题讨论】:

    标签: python python-3.x server-sent-events


    【解决方案1】:

    2.0.0rc2 版本增加了对 Python 3.6+ 的支持

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-12
      • 2016-04-26
      • 2012-03-10
      • 2017-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多