python-twisted:写一个广播员

时间:2014-08-22 14:37:18

标签: python twisted

即时学习python twisted,我参考这个例子:

#!/usr/bin/env python

# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
An example demonstrating how to send and receive UDP broadcast messages.

Every second, this application will send out a PING message with a unique ID.
It will respond to all PING messages with a PONG (including ones sent by
itself). You can tell how many copies of this script are running on the local
network by the number of "RECV PONG".

Run using twistd:

$ twistd -ny udpbroadcast.py
"""

from uuid import uuid4

from twisted.application import internet, service
from twisted.internet.protocol import DatagramProtocol
from twisted.python import log



class PingPongProtocol(DatagramProtocol):
    noisy = False

    def __init__(self, controller, port):
        self.port = port


    def startProtocol(self):
        self.transport.setBroadcastAllowed(True)


    def sendPing(self):
        pingMsg = "PING {0}".format(uuid4().hex)
        self.transport.write(pingMsg, ('<broadcast>', self.port))
        log.msg("SEND " + pingMsg)


    def datagramReceived(self, datagram, addr):
        if datagram[:4] == "PING":
            uuid = datagram[5:]
            pongMsg = "PONG {0}".format(uuid)
            self.transport.write(pongMsg, ('<broadcast>', self.port))
            log.msg("RECV " + datagram)
        elif datagram[:4] == "PONG":
            log.msg("RECV " + datagram)



class Broadcaster(object):

    def ping(self, proto):
        proto.sendPing()


    def makeService(self):
        application = service.Application('Broadcaster')

        root = service.MultiService()
        root.setServiceParent(application)

        proto = PingPongProtocol(controller=self, port=8555)
        root.addService(internet.UDPServer(8555, proto))
        root.addService(internet.TimerService(1, self.ping, proto))

        return application


application = Broadcaster().makeService()

我注意到,对于这个广播公司示例,我们需要以twistd -ny udpbroadcast.py

运行

如果我作为一个包运行,我该如何修改代码,即:python2.7 -m org.somepackagename。 udpbroadcast?我知道我需要使用反应堆,但我应该怎么做?我看到这个例子使用的是timeservice和UDPServer。我怀疑我必须听reactor.listenUDP(0, protocol) ??

我实际上已将application = Broadcaster().makeService()change def __init__(self, controller, port):评论为def __init__(self, port):并在下方添加了以下代码

from twisted.internet.task import LoopingCall
protocol = PingPongProtocol(port=8009)
lc = LoopingCall(protocol)
reactor.listenUDP(0, protocol)
reactor.run()

但它仍未发送和恢复数据

=============================================== ==========

编辑代码

#!/usr/bin/env python

# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
An example demonstrating how to send and receive UDP broadcast messages.

Every second, this application will send out a PING message with a unique ID.
It will respond to all PING messages with a PONG (including ones sent by
itself). You can tell how many copies of this script are running on the local
network by the number of "RECV PONG".

Run using twistd:

$ twistd -ny udpbroadcast.py
"""

from uuid import uuid4

from twisted.application import internet, service
from twisted.internet.protocol import DatagramProtocol
from twisted.python import log



class PingPongProtocol(DatagramProtocol):
    noisy = False

    # def __init__(self, controller, port):
    def __init__(self, port): # removed controller
        self.port = port


    def startProtocol(self):
        self.transport.setBroadcastAllowed(True)


    def sendPing(self):
        pingMsg = "PING {0}".format(uuid4().hex)
        self.transport.write(pingMsg, ('<broadcast>', self.port))
        log.msg("SEND " + pingMsg)


    def datagramReceived(self, datagram, addr):
        print "RECV:" + datagram
        if datagram[:4] == "PING":
            uuid = datagram[5:]
            pongMsg = "PONG {0}".format(uuid)
            self.transport.write(pongMsg, ('<broadcast>', self.port))
            log.msg("RECV " + datagram)
        elif datagram[:4] == "PONG":
            log.msg("RECV " + datagram)



class Broadcaster(object):

    def ping(self, proto):
        proto.sendPing()


    def makeService(self):
        application = service.Application('Broadcaster')

        root = service.MultiService()
        root.setServiceParent(application)

        proto = PingPongProtocol(port=8009) #removed controller
        root.addService(internet.UDPServer(8009, proto))
        root.addService(internet.TimerService(1, self.ping, proto))

        return application


# application = Broadcaster().makeService() #commented. to use the code below

protocol = PingPongProtocol(port=8009)

from twisted.internet.task import LoopingCall
lc = LoopingCall(protocol)
# lc.start(3) #commented cos its throwing error

from twisted.internet import reactor
reactor.listenUDP(8009, protocol)
reactor.run()

0 个答案:

没有答案