首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

python 每隔一秒循环发10条数据 为什么是10条一起发出去的

2013-03-01 
python 每隔1秒循环发10条数据 为什么是10条一起发出去的?python 每隔1秒循环发10条数据 为什么是10条一起

python 每隔1秒循环发10条数据 为什么是10条一起发出去的?
python 每隔1秒循环发10条数据 为什么是10条一起发送的?
我用的是twisted的框架, 我想没隔一秒就发送一条出去  而不是等10条一起发送,怎么解决?

这个就有点像nagle算法了 但是python中不知道怎么关闭
[解决办法]

引用:
引用:然后
self.transport.flush()
调用flush 把缓冲中的字符发送出去

我用了 但是报错 说没这个函数
  File "D:/prototype/baoTset/testVsim.py", line 36, in connectionMade
    self.transport.flush()……

#
import time
from twisted.internet import protocol, reactor, defer,threads
class Echo(protocol.Protocol):
def connectionMade(self):
#1. writeSomeData
def writeSomeData():
i=10
while i:
self.transport.writeSomeData(time.strftime('%H:%M:%S',time.localtime(time.time())))
self.transport.writeSomeData('\r\n')
time.sleep(2)
i-=1
writeSomeData()
#2, threads.deferToThread
def write():
i=10
while i:
self.transport.write(time.strftime('%H:%M:%S',time.localtime(time.time())))
self.transport.write('\r\n')
time.sleep(2)
i-=1
threads.deferToThread(write)

class EchoFactory(protocol.Factory):
def buildProtocol(self, addr):
return Echo()

reactor.listenTCP(8000, EchoFactory())
reactor.run()

写了两种方法 writeSomeData,deferToThread

telnet localhost 8000 可以看到数据每隔2秒输出一次,不知道是不是要这种效果

[解决办法]
你的代码里写得是循环了一下boss_id然后每次循环都是10秒之后发消息,因为循环很快,所以感觉上就是一起发出去了,简单的在callLater里多加个1秒延时就可以了。切记,twisted下面不要在主线程里用sleep这种线程模型的东西。

    def connectionMade(self):
        logging.info('Got connection from :' + repr(self.transport.client))
        boss_id = 0
        while boss_id < self.count:
            boss_id = boss_id + 1
                       msg = "{"method":"getSimInfo","id":%d"%boss_id + ","params":{"simBankAddress":1,"bladeLogicalAddress":1,"simAddress":%d}}"%boss_id
            json_data = struct.pack('>cH{msg_len}s'.format(msg_len = len(msg)), '\x00', len(msg), msg)
            reactor.callLater(9 + boss_id, self.transport.write, json_data)
            #self.transport.write(json_data)
            self.idSendList.append(boss_id)
            logging.info('send :' + repr(json_data))
            #time.sleep(5)

[解决办法]
网络框架都是epoll单线程的,python多线程因为GIL锁而伪并行, 所以你开线程会影响epoll线程的执行CPU时间。

热点排行