编辑:由于我通过文本附加文件没有正确保存,我决定重写我最初希望的方式并将文件保存为流:Twisted server:
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% 的文件,然后似乎就是这样,我想我写的文件不正确。
扭曲的服务器:
from twisted.internet import reactor, protocol
import os,json
class Echo(protocol.Protocol):
def dataReceived(self, data):
try:
print format(json.loads(data))
print "got jason"
self.transport.write("ready")
except:
print "filedata incoming!"
f = open("test.png","a")
f.write(data)
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()
扭曲的客户端:
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,服务器接收数据包并告诉发送客户端'ok',然后客户端发送文件;然后服务器接收文件并将其写入磁盘。我只是在测试,所以这个程序可能没有多大意义,尤其是文件附加的使用——但我注意到在传输和最终写入之后,文件的大小与原始文件的大小差不多,但不完全和小了大约 300 字节,因此几乎没用。我是否错误地发送了文件?还是只是写错了?哦,是的,我正在同一台计算机上测试服务器和客户端。
最终,我计划在两台本地计算机之间发送大至 1GB 的文件以进行备份,并希望将文件作为数据流写入,我不喜欢我正在使用的附加方法,但我不知道如何在不实际打开文件的情况下引用文件对象,这是我第一次收到 json 对象时才想做的事情。
谢谢!