2
我需要連接到服務器(例如SMPP服務器),並定期發送數據每2秒,下面的代碼:Python的asyncore客戶定期發送數據到服務器
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分鐘,我不明白爲什麼它不獲取其充分利用線程人口剛過緩衝區?
但是,當從SClient對象內部調用sendCommand時,asyncore會檢測到緩衝區不是空的,並將數據實時發送到服務器。 –
這不是我閱讀文檔的方式。 「writeable」方法是「...每次在異步循環周圍調用以確定是否應將通道的套接字添加到發生寫入事件的列表中。」嘗試在示例代碼中將超時設置爲2秒(在輪詢之前,您有15個發送命令* 2秒)。 – Mark