Zainab
Zainab

Reputation: 11

Tornado-eventsource server not getting messages

I am working on Rabbitmq and Server sent events for this I use tornado-eventsource (https://github.com/guilhermef/tornado-eventsource/tree/master/tornado_eventsource) from this code I tried to make my connection of EventSource. When my server receives messages it suooise to send it to client but it gives this error message and messages are not watched by server to send But I guess due to a change in versions as I use python3 I get an error.

File "C:\Users\Admin\AppData\Local\Programs\Python\Python37\lib\site-packages\tornado_eventsource\handler.py", line 71, in write_message if isinstance(msg, str) or isinstance(msg, unicode): NameError: name 'unicode' is not defined

Please guide me regards this.

Server side code here:

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...')

Upvotes: 1

Views: 134

Answers (1)

Guilherme Souza
Guilherme Souza

Reputation: 78

Support to Python 3.6+ was added on the version 2.0.0rc2

Upvotes: 0

Related Questions