0
私は非同期のTCPクライアントとして実装しようとしています - サーバーモデルは、Pythonで。これはasyncoreモジュールを使用した私の最初の例です。誰かが私を提供できるのであれば、私はいくつかの説明が必要です。python asyncoreクライアントの例
私は、次の要件があります を[クライアント]
- は、クライアントのインスタンスを開始 - サーバは、サーバが出てくるのを待つ他に実行されている場合は、サーバーに接続します。
- サーバーからデータを送受信する必要があります。
- ソケットでデータを受信するたびに通知します。
私はネットからのサンプル例を実行しようとしたが、いくつかの疑問だった:
import asyncore
import logging
import socket
from cStringIO import StringIO
import urlparse
class Client(asyncore.dispatcher):
def __init__(self,host):
self.logger = logging.getLogger()
self.write_buffer = ""
self.read_buffer = StringIO()
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
address = (host, 80)
self.logger.debug('connecting to %s', address)
self.connect(address)
def handle_connect(self):
self.logger.debug('handle_connect()')
def handle_close(self):
self.logger.debug('handle_close()')
self.close()
def writable(self):
is_writable = (len(self.write_buffer) > 0)
if is_writable:
self.logger.debug('writable() -> %s', is_writable)
return is_writable
def readable(self):
self.logger.debug('readable() -> True')
return True
def handle_write(self):
sent = self.send(self.write_buffer)
self.logger.debug('handle_write() -> "%s"', self.write_buffer[:sent])
self.write_buffer = self.write_buffer[sent:]
def handle_read(self):
data = self.recv(8192)
self.logger.debug('handle_read() -> %d bytes', len(data))
self.read_buffer.write(data)
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG,
format='%(name)s: %(message)s',
)
clients = Client("127.0.0.1")
logging.debug('LOOP STARTING')
asyncore.loop()
logging.debug('LOOP DONE')
- データがソケットから を読み可能な状態になったとき、ディスパッチャクラスは通知しない方法を。そのシナリオではhandle_readが呼び出されていますか?
- ビジー状態のポーリングメカニズムですか?ソケットが アイドル状態であっても、それは私のCPU全体を食べますか?
- 上記の例では、サーバーが起動するのを待っていません。どのようにこれを行うことができますか?
- クライアントからソケットにデータを書き込む方法はありますか?