开发者

sending random data with Twisted

开发者 https://www.devze.com 2023-01-23 06:23 出处:网络
I\'m trying to create an application that maxes out the user\'s downstream by continuously sending data.Is there a variable that tells how many bytes are in the out buffer?And I say \"out buffer,\" bu

I'm trying to create an application that maxes out the user's downstream by continuously sending data. Is there a variable that tells how many bytes are in the out buffer? And I say "out buffer," but is there a bette开发者_StackOverflowr term for the data that is being buffered before its sent to the client? Am I going about this the right way? It doesn't seem practical to self.transport.write() 100 megabytes.


The way Twisted exposes this information is with a pair of APIs commonly referred to as "producers" and "consumers". You can find a document about them on the Twisted site.

In your case, a "pull producer" is probably appropriate, since your random data probably isn't coming from an event source, but can be generated on demand. A rough sketch might look something like this (and hopefully the above linked document will explain why this works):

from os import urandom

from zope.interface import implements

from twisted.internet.interfaces import IPullProducer

class RandomProducer(object):
    implements(IPullProducer)

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


    def resumeProducing(self):
        self.consumer.write(urandom(2 ** 16))


    def stopProducing(self):
        pass

So, for example, when a connection is set up, you can register this producer with the transport:

from twisted.internet.protocol import Protocol

class RandomProtocol(Protocol):
    def connectionMade(self):
        self.transport.registerProducer(RandomProducer(self.transport), False)

This will send random data at the client as fast as possible.

0

精彩评论

暂无评论...
验证码 换一张
取 消