Python Tornado:从另一个类发送websocket消息

时间:2018-09-30 04:46:09

标签: python websocket tornado

有一个使用(Python 3.6)Tkinter&Tornado的应用程序。希望它在按下按钮时发送websocket消息。

sendSocket在我的类中处理接口。我可以正常打开套接字,并且可以将数据发送到套接字处理程序中。此外,它可以从我的RequestHandler提供我的html文件。

我可以看到我的代码点击了sendSocketMessage行。但是,我从来没有从SocketHandler.send_message def中获得打印信息。控制台中没有错误。

    def sendSocketMessage(self, data = "whatever"):
        print("sending")
        #WebSocketeer.send_message(data)        
        ioloop.IOLoop.current().add_callback(WebSocketeer.send_message, data)

class WebSocketeer(websocket.WebSocketHandler):    
    def open(self):
       print("WebSocket opened")

    def on_message(self, message):
       print("got message: " + message)

    def on_close(self):
       print("WebSocket closed")

    @classmethod
    def send_message(self, message):
        print("sending message: " + message)
        for session_id, session in self.session.server._sessions._items.iteritems():
            session.conn.emit(event, message)

基于这些SO响应的代码

2 个答案:

答案 0 :(得分:0)

找到了一种使其在此处工作的方法:How to run functions outside websocket loop in python (tornado)

但是我仍然想知道为什么add_callback不起作用-从我的读物来看,这是推荐的方法。

答案 1 :(得分:0)

这就是我正在做的工作,摘自:https://github.com/tornadoweb/tornado/issues/2802

clients = [];
class WSHandler(tornado.websocket.WebSocketHandler):
    
    def open(self):
        print('connection opened...')
        clients.append(self);

    def on_message(self, message):
        self.write_message("The server says: " + message + " back at you")
        print('received:', message)

    def on_close(self):
        clients.remove(self);
        print('connection closed...')

    @classmethod
    def send_message(self, message):
        print("sending message: " + message)
        for client in clients:
            client.write_message(message);
        #for session_id, session in self.session.server._sessions._items.iteritems():
        #    session.conn.emit(event, message);
        return True;

def sendRandom():
    global thread, data;
    try:
        print("sendRandom()");
        time.sleep(0.125);
        n = random.randint(0,1000);
        data = str(n);
        data = {"msg":"data","data":data};
        if eventLoop is not None:
            #If response needed
                #sendData(eventLoop,WSHandler.send_message,json.dumps(data));
            #else
            eventLoop.add_callback(WSHandler.send_message,json.dumps(data));
    except:
        print("Err");
        traceback.print_exc();

clients = [];

def sendData(loop,f,*a,**kw):
    print("%s %s" % (type(loop),type(f)));
    concurrent_future = concurrent.futures.Future();
    async def wrapper():
        try:
           rslt = f(*a,**kw);
        except Exception as e:
            concurrent_future.set_exception(e);
        else:
            concurrent_future.set_result(rslt);
    loop.add_callback(wrapper);
    return concurrent_future.result();

eventLoop = None;

application = tornado.web.Application([
   (r'/data', WSHandler),
    ])

def startServer():
    global eventLoop;
    try:
        print("Starting server @%s:%d" %("localhost",9090));  
        asyncio.set_event_loop(asyncio.new_event_loop());
        eventLoop = tornado.ioloop.IOLoop();
        application.listen(9090)
        eventLoop.start();
    except KeyboardInterrupt:
        print("^C");
    except:
        print("ERR");
        traceback.print_exc();

if __name__ == "__main__":
    thread = Thread(target=startServer,);
    thread.setDaemon(True);
    thread.start();
    time.sleep(5);
    while True:
        sendRandom();