1

我有一个带有 iOS 客户端的 Python tcp 服务器。它能够发送和接收数据,我遇到的唯一问题可能是编码。我正在尝试通过 TCP 将 JPEG 发送到 Python 服务器并将数据写入服务器上的 JPEG。jpeg不断损坏。

客户端 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]];



        }];

这是python(扭曲的)服务器代码:

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()
4

1 回答 1

2

TCP 是一种面向流的协议。它没有消息(因此它没有稳定的消息边界)。 dataReceived用一些字节调用 - 至少一个,但还有多少你真的不知道。

您不能只将传递给dataReceived的任何内容视为完整的图像数据。它是来自图像数据的一些字节。机会dataReceived将被重复调用,每次都从图像数据中获取更多字节。您必须将传递给这些多次调用的数据重新组合成完整的图像数据。

于 2014-08-31T21:17:14.330 回答