编辑:由于我是通过文本附加文件,文件没有正确保存,所以我决定重写我最初希望的方式,并将文件保存为流: Twisted服务器:
from twisted.internet import reactor, protocol
import os,json
class Echo(protocol.Protocol):
f = file
def dataReceived(self, data):
try:
try:
print format(json.loads(data))
print "got jason"
self.f=open("test.png","wb")
self.transport.write("ready")
except:
print "filedata incoming!"
self.f.write(data)
except:
print "unknown error" #happens if we don't receive json first
def connectionLost(self, reason):
if self.f!=file:self.f.close()
def main():
"""This runs the protocol on port 8000"""
factory = protocol.ServerFactory()
factory.protocol = Echo
reactor.listenTCP(8000,factory)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
Twisted发送了99.9%的文件,然后似乎就是这样,我认为我写的文件不正确。在
Twisted服务器:
^{pr2}$扭曲客户端:
from twisted.internet import reactor, protocol
import os,json
fname="pic.png"
class EchoClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
fsize = os.path.getsize(fname)
self.transport.write(json.dumps({"file":{"size":fsize}}))
def sendFile(self):
print "sending file"
f = open(fname,"rb")
self.transport.write(f.read())
f.close()
print "closing conn"
self.transport.loseConnection()
def dataReceived(self, data):
"As soon as any data is receive"
print "Server said: ", data
self.sendFile()
def connectionLost(self, reason):
print "connection lost"
class EchoFactory(protocol.ClientFactory):
protocol = EchoClient
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def main():
f = EchoFactory()
reactor.connectTCP("localhost", 8000, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
基本上,服务器正在运行和监听,客户端连接并立即发送json,服务器接收数据包并告诉send client“ok”,然后客户端发送文件;然后服务器接收文件并将其写入磁盘。我注意到,这个文件的大小,并不是很重要,只是在测试后,我写了300个字节的文件。 我是不是把文件发错了?或者只是写错了?是的,我在同一台电脑上测试服务器和客户机。在
最终,我计划在两台本地计算机之间发送1GB大小的文件以备备份,并希望这些文件以数据流的形式写入,我不喜欢我使用的append方法,但我不知道如何引用file对象而不实际打开文件,这是我第一次收到json对象时才想做的事情。在
谢谢!在
问题是您希望
dataReceived
同时接收所有数据。互联网不是这样工作的:see this Twisted FAQ for an explanation of why this is so and how to fix your code。在你在开门”测试.png“用于附加文本。这是故意的吗?在
您还有一个空的
except
,这是一个坏主意,因为它捕获所有异常。只捕获您期望的异常。在相关问题 更多 >
编程相关推荐