0

这是我的客户:

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()

我的问题是在类中的 run 方法中,对于调用时Sender的每个项目,将为所有项目调用,并且仅对最后一个项目调用。artist.artistListsendArtist()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
4

1 回答 1

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()
于 2013-09-03T20:52:55.863 回答