꼬인 파이썬의 문제 - 이진 데이터 전송
문제
내가하려는 것은 상당히 간단합니다. 클라이언트에서 서버로 파일을 보내십시오. 먼저 클라이언트는 파일에 대한 정보를 보냅니다. 그런 다음 실제 파일을 보냅니다.
이것이 내가 지금까지 한 일입니다.
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()
서버는 사형화 된 객체 만 출력합니다.
{ 'size': 183574528L}
어떻게 되나요? 내가 보내고 싶은 파일에서 20 숯이 무슨 일이 일어 났습니까?
"hej"와 "wa"를 대신 사용하는 경우 대신 보내면 둘 다 (두 번이 아닌 동일한 메시지로) 가져옵니다.
어떤 사람?
해결책
SetRawMode ()를 사용하여 서버를 원시 모드로 설정하므로 콜백 RAWDATARECEIVED는 들어오는 데이터 (Linereceived)로 호출됩니다. RawDatareCeived로받은 데이터를 인쇄하면 파일 컨텐츠를 포함한 모든 것을 볼 수 있지만 Pickle을 호출하여 데이터를 사로화하면 무시됩니다.
서버로 데이터를 보내는 방식을 변경하거나 (NetString 형식을 제안합니다) 피클 직렬화 된 객체 내부의 내용을 전달하고 한 번의 호출로 수행합니다.
self.sendLine(pickle.dumps({"size":filesize, 'content': contents[:20]}))
제휴하지 않습니다 StackOverflow