【问题标题】:Create simple asynchronous server创建简单的异步服务器
【发布时间】:2014-04-28 15:01:49
【问题描述】:

我开始学习 Twisted 并尝试完成我的第一个任务。我有下一个服务器代码:

class TextProtocol(Protocol):

    def connectionMade(self):
        text = self.factory.text
        self.transport.write(text)
        self.transport.loseConnection()

class TextServerFactory(ServerFactory):

    protocol = TextProtocol

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

from twisted.internet import reactor
reactor.listenTCP(4444, TextServerFactory("Twisted"))
reactor.run()

此代码立即向客户端发送文本。但实际上我想通过信件发送数据:如果我们有很多客户端,服务器应该逐个信件发送。我认为 SERVER 日志应该是这样的:

Client #1 connected

Sending "T" to client #1
Sending "w" to client #1

Client #2 connected

Sending "T" to client #2
Sending "i" to client #1
Sending "w" to client #2
Sending "s" to client #1
Sending "i" to client #2

.....

如果我将在协议中创建循环,它将阻塞操作。 你能帮我解决这个问题吗?

【问题讨论】:

    标签: python asynchronous twisted


    【解决方案1】:

    TCP 将根据需要对事物进行分组/批处理/拆分(它试图优化连接),请参阅 Glyph 的 this answer 或更详细的 How can I force a socket to send the data in its buffer 文章

    如果您真的想要这样做,并且介意您试图强迫 TCP 做它不想要的事情,那么 Jean-Paul 的回答是指出您 如果您一次写入一个字符并在每个字符之间等待几秒钟,则可能能够在 TCP 上逐个字符地刷新。

    【讨论】:

      【解决方案2】:

      看看twisted.internet.task.LoopingCalltwisted.internet.IReactorTime.callLater

      【讨论】:

        猜你喜欢
        • 2016-05-12
        • 1970-01-01
        • 2014-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-20
        • 2018-07-28
        相关资源
        最近更新 更多