gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:52:23 25 4
gpt4 key购买 nike

我正在与 this example of an iPhone Chart Server 合作一切都按预期进行。

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

例如,如果我每小时触发一个事件,我希望能够向连接的每个人发送消息,或者如果我想关闭服务器以发送“全局”公告,我是否必须将所有代码放入其中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

最佳答案

假设您注册了一个要在一段时间后执行的回调,那么您可以简单地从 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()

关于Python - 访问类方法(使用twisted),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28141925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com