我下面就写在扭曲的客户机/服务器对位于这里的教程:扭曲客户端协议 - 连接的接口前端
http://twistedmatrix.com/documents/current/core/howto/clients.html
我所拥有的一切工作为我的客户端和服务器的通信,系统使用自定义前缀来表示它进入“对话”的距离。它最初发送一个json字符串来设置会话,然后逐行发送一个文件。这其实只是一项运动而已。
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()
目前,我运行一个终端服务器,并在另一个客户端。正如预期的那样,两个反应器都会启动并通信一次,客户端会传输它的身份json,然后是文件内容,然后终止连接。我无法理解的是如何将这个协议挂接到类似于cmd
接口的东西上,以便在命令结束后产生这些进程。由于客户端中的反应器无限期运行,因此它会执行一次网络对话,然后在反应器中连续循环。
我用Twisted,客户端或服务器构建的所有东西,只是对网络调用做出了响应,所以我想知道什么才是使这个“一次性”客户端协议可以在输入命令上激活的正确方法从cmd
。有人甚至会用这种反应器来做这种事吗?或者为此而扭曲,而不是仅仅手动打开遵循协议的套接字?
编辑
我找到了扭stdio库捕鱼围绕谷歌和SO,但我无法钩住端子输入协议到网络协议。
我有终端协议继承LineReceiver
,并提示正确显示。我已将网络工厂分配给终端协议的factory
对象,然后尝试从提示中调用网络协议的方法。问题是,分配给该属性的连接器对象不使用它应该创建的任何协议方法。
我已经把它在GitHub上为简洁起见:
https://github.com/DeaconDesperado/swfty-share/blob/master/client.py
谢谢...我实际使用您的博客,开始使用一些这=)。我阅读了您提供的链接,但我仍然不确定自己的理解 - 我应该做的是从我写的客户端中创建一个完整的应用程序,并使用操作系统信号通过命令一次性发送执行通信?没有办法使用调用协议,因此可以导入并作为过程运行?谢谢。 – DeaconDesperado
我使用Twisted中的stdio设置了一个协议,以从终端获取输入,我已经取得了一些进展......只是需要使其与网络协议以某种方式进行通信。 – DeaconDesperado