Асинхронный клиент Python для отправки периодических данных на сервер

Мне нужно подключиться к серверу (например, smpp-серверу) и отправлять периодические данные каждые 2 секунды, вот код:

import asyncore, socket, threading, time

class SClient(asyncore.dispatcher):
    buffer = ""
    t = None

    def __init__(self, host):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect( (host, 25) )

        print "sending data from __init__"
        self.sendCommand("data_init")
        self.t = SenderThread(self)
        self.t.start()

    def sendCommand(self, command):
        self.buffer = command

    def handle_close(self):
        self.close()
        self.t.stop()

    def handle_read(self):
        print self.recv(8192)

    def writable(self):
        print 'asking for writable ? len='+str(len(self.buffer))
        return (len(self.buffer) > 0)

    def handle_write(self):
        print "writing to socket"
        sent = self.send(self.buffer)
        self.buffer = self.buffer[sent:]
        print "wrote "+str(sent)+" to socket"

class SenderThread(threading.Thread):
    _stop = False

    def __init__(self, client):
        super(SenderThread,self).__init__()
        self.client = client

    def stop(self):
        self._stop = True

    def run(self):
        counter = 0
        while self._stop == False:
            counter += 1
            time.sleep(1)
            if counter == 2:
                print "sending data from thread"
                self.client.sendCommand("data_thread")
                counter = 0

client = SClient('127.0.0.1')
asyncore.loop()

Вот вывод при запуске:

$ python test.py 
sending data from __init__
asking for writable ? len=9
writing to socket
wrote 9 to socket
asking for writable ? len=0
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
asking for writable ? len=11
writing to socket
wrote 11 to socket
asking for writable ? len=0
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
asking for writable ? len=11
writing to socket
wrote 11 to socket
asking for writable ? len=0
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread
sending data from thread

Мой поток отправляет данные на сервер каждые 2 секунды через переменную буфера, но asyncore вызывает доступ для записи и handle_write ровно каждую 1 минуту, я не понимаю, почему он не извлекает буфер сразу после его заполнения из потока?


person zfou    schedule 14.08.2011    source источник


Ответы (1)


Посмотрите документацию по методу цикла asyncore.

Аргумент тайм-аута устанавливает параметр тайм-аута для соответствующего вызова select() или poll(), измеряемый в секундах; по умолчанию 30 секунд.

Он запускает handle_write каждые 30 секунд.

person Mark    schedule 14.08.2011
comment
Но при вызове sendCommand из объекта SClient asyncore обнаруживает, что буфер не пуст, и отправляет данные на сервер в режиме реального времени. - person zfou; 14.08.2011
comment
Я не так читаю документы. Метод записи вызывается каждый раз вокруг асинхронного цикла, чтобы определить, следует ли добавить сокет канала в список, в котором могут происходить события записи. Попробуйте установить тайм-аут на 2 секунды в вашем примере кода (у вас есть 15 команд отправки * 2 секунды, прежде чем он будет опрошен). - person Mark; 14.08.2011