首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python的asyncore使用可变超时定期发送数据。有没有更好的方法?

Python的asyncore使用可变超时定期发送数据。有没有更好的方法?
EN

Stack Overflow用户
提问于 2009-06-24 06:11:05
回答 5查看 8.3K关注 0票数 8

我想编写一个客户端可以连接并接收定期更新的服务器,而不需要轮询。我在使用asyncore时遇到的问题是,如果在调用dispatcher.writable()时没有返回true,则必须等到asyncore.loop超时之后(默认为30s)。

我试图解决这个问题的两种方法是: 1)将超时时间减少到一个较低的值;2)查询连接的下次更新时间并生成足够的超时值。但是,如果您在‘man2select_tut’中引用'Select Law‘,它会声明,“您应该始终尝试使用select()而不超时。”

有没有更好的方法来做这件事?也许是扭曲的?我想试着避免额外的线程。我将在这里包含变量超时示例:

代码语言:javascript
运行
复制
#!/usr/bin/python

import time
import socket
import asyncore


# in seconds
UPDATE_PERIOD = 4.0

class Channel(asyncore.dispatcher):

    def __init__(self, sock, sck_map):
        asyncore.dispatcher.__init__(self, sock=sock, map=sck_map)
        self.last_update = 0.0  # should update immediately
        self.send_buf = ''
        self.recv_buf = ''

    def writable(self):
        return len(self.send_buf) > 0

    def handle_write(self):
        nbytes = self.send(self.send_buf)
        self.send_buf = self.send_buf[nbytes:]

    def handle_read(self):
        print 'read'
        print 'recv:', self.recv(4096)

    def handle_close(self):
        print 'close'
        self.close()

    # added for variable timeout
    def update(self):
        if time.time() >= self.next_update():
            self.send_buf += 'hello %f\n'%(time.time())
            self.last_update = time.time()

    def next_update(self):
        return self.last_update + UPDATE_PERIOD


class Server(asyncore.dispatcher):

    def __init__(self, port, sck_map):
        asyncore.dispatcher.__init__(self, map=sck_map)
        self.port = port
        self.sck_map = sck_map
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.bind( ("", port))
        self.listen(16)
        print "listening on port", self.port

    def handle_accept(self):
        (conn, addr) = self.accept()
        Channel(sock=conn, sck_map=self.sck_map)

    # added for variable timeout
    def update(self):
        pass

    def next_update(self):
        return None


sck_map = {}

server = Server(9090, sck_map)
while True:
    next_update = time.time() + 30.0
    for c in sck_map.values():
        c.update()  # <-- fill write buffers
        n = c.next_update()
        #print 'n:',n
        if n is not None:
            next_update = min(next_update, n)
    _timeout = max(0.1, next_update - time.time())

    asyncore.loop(timeout=_timeout, count=1, map=sck_map)
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2009-06-24 07:10:19

"select法则“不适用于您的情况,因为您不仅有客户端触发的(纯服务器)活动,而且还有时间触发的活动-这正是select超时的原因。法律真正应该说的是“如果你指定了一个超时,确保当超时到来时,你实际上必须做一些有用的事情”。该法律旨在防止繁忙等待;您的代码不会繁忙等待。

我不会将_timeout设置为最大值0.1和下一次更新时间,而是设置为最大值0.0和下一次超时。如果在你进行更新时更新周期已经过期,你应该立即进行特定的更新。

您可以将所有通道存储在优先级队列中(按下一次更新时间排序),然后只对最早的通道运行更新(直到找到更新时间尚未到达的通道),而不是每次都询问每个通道是否要更新。为此,您可以使用heapq模块。

您还可以节省一些系统调用,方法是不让每个通道都询问当前时间,而是只轮询当前时间一次,并将其传递给.update。

票数 4
EN

Stack Overflow用户

发布于 2010-04-24 15:56:52

也许你可以用sched.scheduler这样做,就像这样(注意:未测试):

代码语言:javascript
运行
复制
import sched, asyncore, time

# Create a scheduler with a delay function that calls asyncore.loop
scheduler = sched.scheduler(time.time, lambda t: _poll_loop(t, time.time()) )

# Add the update timeouts with scheduler.enter
# ...

def _poll_loop(timeout, start_time):  
  asyncore.loop(timeout, count=1)
  finish_time = time.time()
  timeleft = finish_time - start_time
  if timeleft > timeout:  # there was a message and the timeout delay is not finished
    _poll_loop(timeleft, finish_time) # so wait some more polling the socket

def main_loop():
  while True:
    if scheduler.empty():
      asyncore.loop(30.0, count=1) # just default timeout, use what suits you
      # add other work that might create scheduled events here
    else:
      scheduler.run()
票数 4
EN

Stack Overflow用户

发布于 2011-02-10 20:08:58

这基本上是demiurgus的解决方案,粗糙的边缘是圆形的。它保留了他的基本思想,但防止了RuntimeErrors和繁忙循环,并进行了测试。编辑:解决了在_delay期间修改调度程序的问题

代码语言:javascript
运行
复制
class asynschedcore(sched.scheduler):
    """Combine sched.scheduler and asyncore.loop."""
    # On receiving a signal asyncore kindly restarts select. However the signal
    # handler might change the scheduler instance. This tunable determines the
    # maximum time in seconds to spend in asycore.loop before reexamining the
    # scheduler.
    maxloop = 30
    def __init__(self, map=None):
        sched.scheduler.__init__(self, time.time, self._delay)
        if map is None:
            self._asynmap = asyncore.socket_map
        else:
            self._asynmap = map
        self._abort_delay = False

    def _maybe_abort_delay(self):
        if not self._abort_delay:
            return False
        # Returning from this function causes the next event to be executed, so
        # it might be executed too early. This can be avoided by modifying the
        # head of the queue. Also note that enterabs sets _abort_delay to True.
        self.enterabs(0, 0, lambda:None, ())
        self._abort_delay = False
        return True

    def _delay(self, timeout):
        if self._maybe_abort_delay():
            return
        if 0 == timeout:
            # Should we support this hack, too?
            # asyncore.loop(0, map=self._asynmap, count=1)
            return
        now = time.time()
        finish = now + timeout
        while now < finish and self._asynmap:
            asyncore.loop(min(finish - now, self.maxloop), map=self._asynmap,
                          count=1)
            if self._maybe_abort_delay():
                return
            now = time.time()
        if now < finish:
            time.sleep(finish - now)

    def enterabs(self, abstime, priority, action, argument):
        # We might insert an event before the currently next event.
        self._abort_delay = True
        return sched.scheduler.enterabs(self, abstime, priority, action,
                                        argument)

    # Overwriting enter is not necessary, because it is implemented using enter.

    def cancel(self, event):
        # We might cancel the next event.
        self._abort_delay = True
        return sched.scheduler.cancel(self, event)

    def run(self):
        """Runs as long as either an event is scheduled or there are
        sockets in the map."""
        while True:
            if not self.empty():
                sched.scheduler.run(self)
            elif self._asynmap:
                asyncore.loop(self.maxloop, map=self._asynmap, count=1)
            else:
                break
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1036646

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档