为什么tcp消息不能写入twisted中的传输?

2024-05-28 19:29:42 发布

您现在位置:Python中文网/ 问答频道 /正文

你知道吗服务器.py你知道吗

 # This is the Twisted Fast Poetry Server, version 1.0

    import optparse, os

    from twisted.internet.protocol import ServerFactory, Protocol


    def parse_args():
        usage = """usage: %prog [options] poetry-file

    This is the Fast Poetry Server, Twisted edition.
    Run it like this:

      python fastpoetry.py <path-to-poetry-file>

    If you are in the base directory of the twisted-intro package,
    you could run it like this:

      python twisted-server-1/fastpoetry.py poetry/ecstasy.txt

    to serve up John Donne's Ecstasy, which I know you want to do.
    """

        parser = optparse.OptionParser(usage)

        help = "The port to listen on. Default to a random available port."
        parser.add_option('--port', type='int', help=help)

        help = "The interface to listen on. Default is localhost."
        parser.add_option('--iface', help=help, default='localhost')

        options, args = parser.parse_args()

        if len(args) != 1:
            parser.error('Provide exactly one poetry file.')

        poetry_file = args[0]

        if not os.path.exists(args[0]):
            parser.error('No such file: %s' % poetry_file)

        return options, poetry_file


    class PoetryProtocol(Protocol):

        def __init__(self, factory):
            self.factory = factory

        def connectionMade(self):
            self.factory.pushers.append(self)
            #self.transport.write("self.factory.poem")
            #self.transport.write(self.factory.poem)
            #self.transport.loseConnection()



    class PoetryFactory(ServerFactory):

        #protocol = PoetryProtocol


        def __init__(self, poem):
            self.poem = poem
            self.pushers = []#

        def buildProtocol(self, addr):
            return PoetryProtocol(self)



    def main():
        options, poetry_file = parse_args()

        poem = open(poetry_file).read()

        factory = PoetryFactory(poem)


        from twisted.internet import reactor

        port = reactor.listenTCP(options.port or 0, factory,
                                 interface=options.iface)

        print 'Serving %s on %s.' % (poetry_file, port.getHost())

        reactor.run()

        factory.pushers[0].transport.write("hey")#########why is this message not received on the client?




    if __name__ == '__main__':
        main()

当建立连接时,我已经创建了一个名为pusher(在工厂中)的协议列表。当我尝试写入时,消息没有到达客户端接收到的数据中。为什么?你知道吗


Tags: thetoselfparserpoetryisportfactory
1条回答
网友
1楼 · 发布于 2024-05-28 19:29:42

您在运行reactor之后立即调用factory.pushers[0].transport.write,但只有当客户端连接到服务器时,协议实例才会添加到工厂推送器列表中

如果要在建立连接时写入客户端,请取消对connectionMade处理程序中第二行的注释:

    def connectionMade(self):
        self.factory.pushers.append(self)
        self.transport.write("hey")

相关问题 更多 >

    热门问题