题
我试图做的是相当简单:从客户端发送文件到服务器。首先,客户发送有关文件的信息 - 它的大小是。然后,它发送实际文件。
这是我到目前为止已经完成的:
Server.py
from twisted.internet import reactor, protocol
from twisted.protocols.basic import LineReceiver
import pickle
import sys
class Echo(LineReceiver):
def connectionMade(self):
self.factory.clients.append(self)
self.setRawMode()
def connectionLost(self, reason):
self.factory.clients.remove(self)
def lineReceived(self, data):
print "line", data
def rawDataReceived(self, data):
try:
obj = pickle.loads(data)
print obj
except:
print data
#self.transport.write("wa2")
def main():
"""This runs the protocol on port 8000"""
factory = protocol.ServerFactory()
factory.protocol = Echo
factory.clients = []
reactor.listenTCP(8000,factory)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
Client.py
import pickle
from twisted.internet import reactor, protocol
import time
import os.path
from twisted.protocols.basic import LineReceiver
class EchoClient(LineReceiver):
def connectionMade(self):
file = "some file that is a couple of megs"
filesize = os.path.getsize(file)
self.sendLine(pickle.dumps({"size":filesize}))
f = open(file, "rb")
contents = f.read()
print contents[:20]
self.sendLine(contents[:20])
f.close()
# self.sendLine("hej")
# self.sendLine("wa")
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()
服务器将仅输出反序列化对象:
{ '尺寸':183574528L}
为什么?发生了什么,从该文件的20个字符我想送?
如果使用“HEJ”和“わ”发送相反,我会得到他们两者(在同一消息中,而不是两次)。
有人?
解决方案
您已经设置你的服务器的原始模式setRawMode(),所以回调rawDataReceived被称为与输入数据(不lineReceived)。如果您打印您在rawDataReceived接收到的数据,你看到的一切,包括文件内容,但正如你所说泡菜反序列化的数据,它被忽略了。
你要么改变你将数据发送到服务器的方式(我建议的净字符串格式)或者你通过了泡菜序列化对象里面的内容,并在一个调用做到这一点。
self.sendLine(pickle.dumps({"size":filesize, 'content': contents[:20]}))
不隶属于 StackOverflow