通过TCP发送JPEG NSData到Python服务器
问题描述:
我有一个拥有iOS客户端的Python tcp服务器。它能够发送数据和接收,我遇到的唯一问题可能是编码。我试图通过TCP发送JPEG到Python服务器,并将数据写入服务器上的JPEG。 jpeg不断腐败。通过TCP发送JPEG NSData到Python服务器
客户端的OBJ-C代码:
[self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection
completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
UIImage *image = [[UIImage alloc] initWithData:imageData];
iv = [[UIImageView alloc] initWithImage:image];
[iv setFrame:[[self view]frame]];
ConnectionManager *netCon = [ConnectionManager alloc];
conMan = netCon;
[conMan initNetworkCommunication];
[conMan.outputStream write:(const uint8_t *)[imageData bytes] maxLength:[imageData length]];
}];
这里是蟒(扭曲)的服务器代码:
from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor
class IphoneChat(Protocol):
def connectionMade(self):
self.factory.clients.append(self)
print "clients are ", self.factory.clients
def connectionLost(self, reason):
self.factory.clients.remove(self)
def dataReceived(self, data):
file = open('test.jpeg','w')
file.write(data)
file.close()
factory = Factory()
factory.clients=[]
factory.protocol = IphoneChat
reactor.listenTCP(2000, factory)
print "Iphone Chat server started"
reactor.run()
答
TCP是一个面向流的协议。它没有消息(因此它没有稳定的消息边界)。用一些字节调用dataReceived
- 至少有一个字节,但比你不能真正知道的要多得多。
您不能仅仅将传递给dataReceived
的任何东西视为完整的图像数据。它是来自图像数据的一些字节。机会是dataReceived
将被重复调用,每次从图像数据中获取更多字节。您必须将传递给这些多次调用的数据重新组装为完整的图像数据。