1

线程融化了我的大脑。我已经看到了几种不同的方法来实现 worker + keepalive 模型,但是很难找出最好的方法。这是代码的简化版本:

def start_thread(function):
    t = Thread(target=function)
    t.setDaemon(True)
    t.start()

def worker:
    run = True
    start_thread(keepalive_fn)

    msg = recv() #blocking
    while msg is not None and run:
        process(msg)
        try:
            msg = recv()
        except:
            if run:
                reconnect()
            break
    else:
        if run:
            reconnect()

def keepalive_fn():
    while run:
        try:
            send('hb')
        except:
            close_connection()
            break
        sleep(heartbeat)

def connect():
    open_connection()
    start_thread(worker)

def reconnect():
    close_connection()
    connect()

connect()

这会像宣传的那样工作吗?有没有更好的办法?请注意,调用 close_connection() 时没有损坏的消息,因为 recv() 已经处理了这种情况。

4

1 回答 1

0

通常的方法是启用 recv() 调用的超时,通过在套接字上设置超时或使用 select/epoll() 调用并使用它来发出轮询和超时。伪:

bool timedOutOnce=false;
while(true){
  result=recv();
  if(result<>timeout){
       timedOutOnce=false;
       if (message<>serverPollReply) processMsg();
  }
  else
    {
      if(timedOutOnce){
         // server has not replied!!
         closeSocket;
         return(NoReplyFromServer);
      }
      else
        {
           // nothing received for a while, so..
           send(serverPollMessage);
           timedOutOnce=true;
        }
    }

}
于 2012-04-21T13:09:21.497 回答