Python - 访问 class 方法(使用扭曲)

Python - access class method (using twisted)

我正在使用 this example of an iPhone Chart Server 并且一切正常。

我想问的是是否以及如何在 IphoneChat class...

之外使用 message(self, message)

例如,如果我每小时触发一个事件,我希望能够向所有连接的人发送一条消息,或者如果我想关闭服务器以发送 'global' 公告,我是否必须将IphoneChat class?

中的所有代码

server.py是这样的:

from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor

class IphoneChat(Protocol):

    def connectionMade(self):
    self.factory.clients.append(self)
    print "clients are ", self.factory.clients

    def connectionLost(self, reason):
    self.factory.clients.remove(self)

# define message handling...

    def dataReceived(self, data):
    a = data.split(':')
    print a
    if len(a) > 1:
        command = a[0]
        content = a[1]

        msg = ""

        if command == "iam":
            #msg = content + " has joined"
            msg = "test1"   

        elif command == "toggle":
            #msg = command + ": " + content
            msg = "test2"

        elif command == "msg":
            msg = command + ": " + content
            print msg

        for c in self.factory.clients:
            c.message(msg)

    def message(self, message):
        self.transport.write(message + '\n')

rt = pollTimer.RepeatedTimer(3, NotifyAllFunction)

factory = Factory()
factory.protocol = IphoneChat
factory.clients = []
reactor.listenTCP(6035, factory)
print "chat server started"
reactor.run()

添加轮询模块:

from threading import Timer

class RepeatedTimer(object):
    def __init__(self, interval, function, *args, **kwargs):
    self._timer     = None
    self.interval   = interval
    self.function   = function
    self.args       = args
    self.kwargs     = kwargs
    self.is_running = False
    self.start()

    def _run(self):
    self.is_running = False
    self.start()
    self.function(*self.args, **self.kwargs)

    def start(self):
    if not self.is_running:
        self._timer = Timer(self.interval, self._run)
        self._timer.start()
        self.is_running = True

    def stop(self):
    self._timer.cancel()
    self.is_running = False

假设您注册了一个要在一段时间后执行的回调,那么您可以简单地从 factory.clients 访问所有客户端并使用他们的 .transport.write() 方法向他们发送消息:

from twisted.internet import task

...
# Rest of the code
...

factory = Factory()
factory.protocol = IphoneChat
factory.clients = []

def broadcast(message):
    for client in factory.clients:
        client.transport.write(message + '\n')

event = task.LoopingCall(broadcast, 'Ping to all users')
event.start(60*60) # call every hour
reactor.listenTCP(6035, factory)
print "chat server started"
reactor.run()