这是我的客户:
class TestClient(asyncore.dispatcher):
#private
_buffer = ""
#public
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((host, port))
self.client = Sender(self)
self.client.start()
# other code
def handle_connect(self):
pass
def handle_close(self):
self.close()
self.client.stop()
def handle_read(self):
try:
data = self.recv(8192)
self.artist.ParseFromString(data)
# print data here
except Exception as ex:
print ex
def writable(self):
return (len(self._buffer) > 0)
def handle_write(self):
sent = self.send(self._buffer)
self.buffer = self._buffer[sent:]
def link(self, name):
return name.replace(' ', '%20')
def sendArtist(self, artist):
print "here"
self._buffer = self.link(artist)
class Sender(threading.Thread):
#private
_stop = False
#public
def __init__(self, client):
super(Sender, self).__init__()
self.client = client
def stop(self):
self._stop = True
def run(self):
i = 0
while self._stop == False and i < len(artists.artistList):
self.client.sendArtist(artists.artistList[i])
i += 1
client = TestClient("127.0.0.1", 7899)
asyncore.loop()
我的问题出在Sender
类的run方法中,artist.artistList
调用sendArtist()
时的每个项目,writable()
将为所有这些项目调用handle_write()
{1}}仅适用于最后一项。
我该怎么做才能为列表中的每个项目调用handle_write()
,而不仅仅是最后一个项目?
这就是现在的工作方式:artists.artistList = [&#34; madonna&#34;,&#34; tiesto&#34;,&#34; atb&#34;];
writable - madonna
writable - tiesto
writable - atb
handle_write - atb
handle_write - atb
...................
handle_write - atb
这就是我想要的:
writable - madonna
handle_write - madonna
writable - tiesto
handle_write - tiesto
writable - atb
handle_write - atb
答案 0 :(得分:1)
Asyncore是一个异步框架,因此,您无法控制何时写入网络。
这里有两个选项:
第二个选项是不言自明的,所以这里是你用常规套接字做的:
import socket
class TestClient(object):
_buffer = ""
def __init__(self, host, port):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((host, port))
def writable(self):
return (len(self._buffer) > 0)
def write(self):
while self.writable():
sent = self.send(self._buffer)
self.buffer = self._buffer[sent:]
def link(self, name):
return name.replace(' ', '%20')
def sendArtist(self, artist):
print "here"
self._buffer = self.link(artist)
self.write()