python twisted:编写广播员

python twisted:编写广播员,python,twisted,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

我正在学习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()
但它仍然没有发送和接收数据

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

编辑代码
#/usr/bin/env python
#版权所有(c)Twisted Matrix Laboratories。
#有关详细信息,请参阅许可证。
"""
演示如何发送和接收UDP广播消息的示例。
每秒钟,此应用程序将发送一条具有唯一ID的PING消息。
它将用PONG响应所有PING消息(包括由
您可以知道此脚本在本地服务器上运行的副本数
按“RECV PONG”的编号进行网络连接。
使用twistd运行:
$twistd-纽约udpbroadcast.py
"""
从uuid导入uuid4
从twisted.application导入internet、服务
从twisted.internet.protocol导入数据报协议
从twisted.python导入日志
乒乓球类协议(DatagramProtocol):
嘈杂=错误
#def\uu init\uuuuuuu(自、控制器、端口):
def _u初始(自身,端口):#已卸下控制器
self.port=端口
def startProtocol(自身):
允许自我运输(真)
def发送(自):
pingMsg=“PING{0}”。格式(uuid4().hex)
self.transport.write(pingMsg,('',self.port))
log.msg(“发送”+pingMsg)
接收到的def数据报(自身、数据报、地址):
打印“RECV:”+数据报
如果数据报[:4]=“PING”:
uuid=数据报[5:]
pongMsg=“PONG{0}”。格式(uuid)
self.transport.write(pongMsg,('',self.port))
log.msg(“RECV”+数据报)
elif数据报[:4]=“PONG”:
log.msg(“RECV”+数据报)
类别广播员(对象):
def ping(自我、原型):
proto.sendPing()
def makeService(自助):
应用程序=服务。应用程序(“广播者”)
root=service.MultiService()
root.setServiceParent(应用程序)
proto=PingPongProtocol(端口=8009)#已卸下控制器
root.addService(internet.UDPServer(8009,proto))
root.addService(internet.TimerService(1,self.ping,proto))
退货申请
#application=Broadcaster()。makeService()#已注释。使用下面的代码
协议=乒乓协议(端口=8009)
从twisted.internet.task导入循环调用
lc=循环呼叫(协议)
#lc.start(3)#由于其抛出错误
从twisted.internet导入
反应堆listenUDP(8009,协议)
反应堆运行()

twistd
是一个Python程序。当您运行
twistd
时,您正在运行Python。你想问什么?为什么你希望它发送任何数据?你也在运行其他程序吗?也许我不清楚我的问题。我在两台机器上运行了该脚本,并使用命令twistd-ny udpbroadcast.py成功地发送和接收了数据。但是我想将脚本作为包运行,所以我将使用命令:python2.7-m org.somepackagename.udpbroadcast。如何修改代码以允许将其作为包运行。udpbroadcast.py绑定到端口8555。重写的版本绑定到端口0-这会导致操作系统随机分配端口。如果您运行两次,每个版本将使用不同的端口,并且它们不会相互通信。哦,天哪,我怎么会错过这个。我把它改成8555,它可以工作了
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()