Python - 访问类方法(使用twisted)

时间:2015-01-25 21:46:17

标签: python twisted

我正在使用this example of an iPhone Chart Server,所有工作都按预期工作。

我想问的是我是否以及如何在message(self, message)课程之外使用IphoneChat ......

例如,如果我每小时都有一个事件触发,我希望能够发送所有连接消息的人,或者如果我想让服务器关闭以发送“全局”公告,我是否必须将所有代码放入IphoneChat班?

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

1 个答案:

答案 0 :(得分:2)

假设您注册了一段时间后要执行的回调,然后您可以从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()