[英]Python's asyncore client send only last element from list inside a thread
这是我的客户:
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
类,对每一个项目artist.artistList
时sendArtist()
被称为writable()
将呼吁所有这些, handle_write()
只为最后一个项目。
我该怎么做才能对列表中的每个项目而不只是最后一个项目调用handle_write()
?
现在是这样工作的:artist.artistList = [“ madonna”,“ tiesto”,“ atb”];
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
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.