如何在Twisted中更新UDP协议实例的值?

时间:2013-11-03 01:41:06

标签: python udp twisted

我正在尝试使用Twisted发送和接收UDP消息,在发送每条消息之后我希望从网络中的其他节点接收相同的消息然后通过一些回调更改“sender”字符串的值然后发送消息之后有了新的价值。我想我应该停止并使用新的数据报协议实例启动它,波纹管代码是我的模板,我想更改heartBeatSenderObj的“sender”值,然后根据它预期未来数据包的新值,但我找不到它的方式,我感谢任何建议和帮助:

from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from twisted.internet.task import LoopingCall
import sys, time

class HeartbeatSender(DatagramProtocol):
    def __init__(self, name, host, port):
        self.name = name
        self.loopObj = None
        self.host = host
        self.port = port

    def startProtocol(self):
        # Called when transport is connected
        # I am ready to send heart beats
        self.loopObj = LoopingCall(self.sendHeartBeat)
        self.loopObj.start(2, now=False)

    def stopProtocol(self):
        "Called after all transport is teared down"
        pass

    def datagramReceived(self, data, (host, port)):
        print "received %r from %s:%d" % (data, host, port)


    def sendHeartBeat(self):
        self.transport.write(self.name, (self.host, self.port))



class HeartbeatReciever(DatagramProtocol):
    def __init__(self):
        pass

    def startProtocol(self):
        "Called when transport is connected"
        pass

    def stopProtocol(self):
        "Called after all transport is teared down"


    def datagramReceived(self, data, (host, port)):
        now = time.localtime(time.time())  
        timeStr = str(time.strftime("%y/%m/%d %H:%M:%S",now)) 
        print "received %r from %s:%d at %s" % (data, host, port, timeStr)



heartBeatSenderObj = HeartbeatSender("sender", "127.0.0.1", 8005)

reactor.listenMulticast(8005, HeartbeatReciever(), listenMultiple=True)
reactor.listenMulticast(8005, heartBeatSenderObj, listenMultiple=True)
reactor.run()

1 个答案:

答案 0 :(得分:1)

datagramReceived的定义如何:

class HeartbeatSender(DatagramProtocol):
    ...
    def datagramReceived(self, data, (host, port)):
        print "received %r from %s:%d" % (data, host, port)
        if data.startswith("change name:"):
            self.name = data[len("change name:"):]

换句话说,HeartbeatSender只是一个普通的Python类,datagramReceived只是该类的常规方法,name只是您拥有的实例的常规属性那个班。事情就像在Python中的任何其他地方一样工作。