ここにある Twisted でのクライアント/サーバー ペアの作成に関するチュートリアルに従っています。
http://twistedmatrix.com/documents/current/core/howto/clients.html
クライアントとサーバーの通信のためにすべてが機能しています。システムはカスタムプレフィックスを使用して、「会話」にどれだけ進んでいるかを示します。最初にjson文字列を送信してセッションをセットアップし、次にファイルを1行ずつ送信します。それは本当に何よりも単なる運動です。
Client.py:
class ClientProtocol(protocol.Protocol):
def connectionMade(self):
json_string = json.dumps({
'uid':ObjectId(),
'lat':43.78,
'lon':-72.5831
},cls=Encoder)
self.transport.write('OPN|'+json_string)
self.fileObject = open('test.csv')
def sendFile(self):
lineData = self.fileObject.readline()
if lineData != '':
self.transport.write('UPD|')
self.transport.write(lineData)
else:
self.transport.write('EOF|done')
def dataReceived(self,data):
if data in ['ELLO','RECVD']:
self.sendFile()
class ClientFactory(protocol.Factory):
def buildProtocol(self,addr):
return ClientProtocol()
if __name__ == '__main__':
point = TCP4ClientEndpoint(reactor,'localhost',5000)
d = point.connect(ClientFactory())
reactor.run()
サーバ:
class TransferProtocol(protocol.Protocol):
ran = 0
def connectionLost(self,reason):
print reason
def connectionMade(self):
self.fileObject = open('output','w')
def dataReceived(self,data):
methods = {'OPN':'open','UPD':'upload','EOF':'endfile'}
if data[0:3] in methods.keys():
func = getattr(self,methods[data[0:3]])
func(data[4:])
def open(self,data):
print 'OPEN %s' % data
self.transport.write('ELLO')
def endfile(self,data):
print 'END %s' % data
self.transport.loseConnection()
def upload(self,data):
self.ran+=1
self.fileObject.write(data)
self.transport.write('RECVD')
class myProtocolFactory(protocol.Factory):
protocol = TransferProtocol
def doStart(self):
pass
def startedConnecting(self, connectorInstance):
print connectorInstance
def buildProtocol(self, address):
print address
return self.protocol()
def clientConnectionLost(self, connection, reason):
print reason
print connection
def clientConnectionFailed(self, connection, reason):
print connection
print reason
def doStop(self):
pass
if __name__ == '__main__':
reactor.listenTCP(5000, myProtocolFactory())
reactor.run()
現在、ある端末でサーバーを実行し、別の端末でクライアントを実行しています。予想どおり、両方のリアクターが起動して一度通信すると、クライアントはその ID json に続いてファイルの内容を送信し、接続を終了します。私が理解できないのは、このプロトコルをcmd
インターフェイスのようなものに「接続」して、終了後にコマンドでこれらのプロセスを生成する方法です。クライアントのリアクターは無期限に実行されるため、ネットワーク通信を 1 回実行すると、リアクター内で継続的にループします。
私がこれまでに Twisted で構築したものはすべて、クライアントでもサーバーでも、ネットワーク呼び出しに応答しただけだったので、cmd
. このような目的でリアクターを使用することさえありますか? または、プロトコルに従うソケットを手動で開くのではなく、その点でまったくねじれていますか?
編集
Twisted stdio ライブラリが google や SO で釣りをしているのを見つけましたが、端末の入力プロトコルをネットワーク プロトコルに接続するのに問題があります。
のターミナル プロトコルを継承しLineReceiver
、プロンプトが正しく表示されます。ネットワーク ファクトリをターミナル プロトコルのfactory
オブジェクトに割り当て、プロンプトからネットワーク プロトコルのメソッドを呼び出そうとしました。問題は、このプロパティに割り当てられたコネクタ オブジェクトが、作成するはずのプロトコルのメソッドをまったく使用しないことです。
簡潔にするために GitHub に置きました。
https://github.com/DeaconDesperado/swfty-share/blob/master/client.py