如何在Python类中使用SignalR接收消息

时间:2017-11-20 17:22:24

标签: python python-3.x signalr

我在下面有以下代码,我使用函数sendMessageToClient1向集线器发送消息,它工作正常,但我无法使用该行从集线器接收消息 self.chat.client.on(“broadcastMessage”,self.sendMessageToClient)。我如何从课堂内接收消息?

from requests import Session
from signalr import Connection
import threading, time, json, logging



class Broker:
    def __init__(self, cli):
        self.cli = cli
        logging.info("registered the cli (main thread)")

    def launch(self):
      try:
        with Session() as session:
            logging.info("inside new session")
            self.connection = Connection("http://localhost:5000/signalr", session)
            logging.info("got the connection")
            self.chat = self.connection.register_hub('chathub')
            logging.info("got the hub")
            self.connection.start()
            logging.info("started the connection")
            self.chat.client.on("broadcastMessage", self.sendMessageToClient)
            logging.info("registered the receiver function")
      except:
        logging.error("error on the creation of the message broker")



    def sendMessageToClient(self, message):
      try:
        logging.info("received message")
        self.chat.server.invoke("ackMessage", message["id"])
        self.cli.sendMessage(message["clientNumber", "messageBody"])
      except:
        logging.error("error receiving a message from the message broker")

    def sendMessageToClient1(self, message):
      try:
        print("sending message " + json.dumps(message))
        self.chat.server.invoke("send", json.dumps(message))
      except:
        logging.error("error sending a message to the broker.")

0 个答案:

没有答案