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

2024-05-15 21:49:25 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是下面的代码,我使用sendMessageToClient函数向集线器发送消息,它工作得很好,但是我不能使用行从集线器接收消息 self.chat.client.on(“广播消息”,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.")

Tags: thefromimportselfinfo消息messagecli