PythonTwistedを使用して単純なTCPサーバー用のクライアントを作成しようとしています。もちろん、私はPythonにかなり慣れていて、Twistedを見始めたばかりなので、すべて間違っている可能性があります。
サーバーはシンプルで、ncまたはtelnetを使用することを目的としています。認証はありません。接続するだけで、シンプルなコンソールを入手できます。いくつかのreadline機能を追加するクライアントを作成したい(履歴とctrl-a / ctrl-eのようなemacsが私が求めているものです)
以下は私が書いたコードで、このようにコマンドラインからnetcatを使用するのと同じように機能しますnc localhost 4118
from twisted.internet import reactor, protocol, stdio
from twisted.protocols import basic
from sys import stdout
host='localhost'
port=4118
console_delimiter='\n'
class MyConsoleClient(protocol.Protocol):
def dataReceived(self, data):
stdout.write(data)
stdout.flush()
def sendData(self,data):
self.transport.write(data+console_delimiter)
class MyConsoleClientFactory(protocol.ClientFactory):
def startedConnecting(self,connector):
print 'Starting connection to console.'
def buildProtocol(self, addr):
print 'Connected to console!'
self.client = MyConsoleClient()
self.client.name = 'console'
return self.client
def clientConnectionFailed(self, connector, reason):
print 'Connection failed with reason:', reason
class Console(basic.LineReceiver):
factory = None
delimiter = console_delimiter
def __init__(self,factory):
self.factory = factory
def lineReceived(self,line):
if line == 'quit':
self.quit()
else:
self.factory.client.sendData(line)
def quit(self):
reactor.stop()
def main():
factory = MyConsoleClientFactory()
stdio.StandardIO(Console(factory))
reactor.connectTCP(host,port,factory)
reactor.run()
if __name__ == '__main__':
main()
出力:
$ python ./console-console-client.py
Starting connection to console.
Connected to console!
console> version
d305dfcd8fc23dc6674a1d18567a3b4e8383d70e
console> number-events
338
console> quit
私は見ました
これは本当にうまくいきませんでした。サンプルコードはうまく機能しますが、ネットワーキングを導入したとき、stdioとの競合状態があるようでした。この古いリンクは同様のアプローチ(別のスレッドでreadlineを実行する)を提唱しているようですが、私はそれをうまく理解していませんでした。
ねじれた巻き貝の侮辱も調べましたが、デモの例以外はうまくいきませんでした。
リードラインサポートを提供する端末ベースのクライアントを作成するための最良の方法は何ですか?
http://twistedmatrix.com/documents/current/api/twisted.conch.stdio.html
有望に見えますが、使い方がわかりません。
http://twistedmatrix.com/documents/current/api/twisted.conch.recvline.HistoricRecvLine.html
また、たとえば上矢印と下矢印の処理をサポートしているようですが、LineReceiverではなくHistoricRecVLineから継承するようにコンソールを切り替えて機能させることができませんでした。
多分ねじれは使用するのに間違ったフレームワークであるか、私はすべての巻き貝のクラスを使用する必要があります。イベント駆動型のスタイルが気に入りました。ツイストクライアントでのサポートのようなreadlineまたはreadlineを持つためのより良い/より簡単なアプローチはありますか?