【问题标题】:Twisted Server/iOS Client sending and receiving imagesTwisted Server/iOS Client 发送和接收图像
【发布时间】:2014-12-30 01:09:07
【问题描述】:

我正在尝试将图像发送到扭曲的服务器并返回到我的 iPhone。我的代码适用于模拟器,但不适用于 iPhone。我不知道为什么。我所做的只是将图像的数据发送到服务器,然后立即返回到我的 iPhone。这是我正在使用的相关代码。


服务器端:


from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor

class IphoneChat(Protocol):
    def connectionMade(self):
        #self.transport.write("""connected""")
        self.factory.clients.append(self)
        print "clients are ", self.factory.clients
    def connectionLost(self, reason):
        self.factory.clients.remove(self)
    def dataReceived(self, data):
        #print "data is ", data
        self.transport.write(data);
    def message(self, message):
        self.transport.write(message + '\n')

factory = Factory()
factory.protocol = IphoneChat
factory.clients = []
reactor.listenTCP(80, factory)
print "Server Started"
reactor.run()

客户端:


@interface LoginScreen : UIViewController <NSStreamDelegate> {
}
@property (strong, nonatomic) NSMutableData *outputData;
@property (strong, nonatomic) IBOutlet UIImageView *testImage;


@implementation LoginScreen : UIViewController
- (void)initNetworkCommunication {
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"avis-mbp", 80, &readStream, &writeStream);
    inputStream = (__bridge NSInputStream *)readStream;
    outputStream = (__bridge NSOutputStream *)writeStream;
    [inputStream setDelegate:self];
    [outputStream setDelegate:self];
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [inputStream open];
    [outputStream open];
}

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
    switch (streamEvent) {
        case NSStreamEventOpenCompleted:
            break;
        case NSStreamEventHasBytesAvailable:
            if (theStream == inputStream) {
                uint8_t buffer[1024];
                long len;
                while ([inputStream hasBytesAvailable]) {
                    len = [inputStream read:buffer maxLength:sizeof(buffer)];
                    if (len > 0) {
                        NSData *output = [[NSData alloc] initWithBytes:buffer length:len];
                        if (nil != output) {
                            [self.appDel.outputData appendBytes:buffer length:len];
                        }
                    }
                }
            }
            break;
        case NSStreamEventErrorOccurred:
            NSLog(@"Can not connect to the host!");
            break;
        case NSStreamEventEndEncountered:
            NSLog(@"Event Ended");
            [theStream close];
            [theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
            theStream = nil;
            break;
        default:
            break;
    }
}

-(IBAction)runNetworkingTest:(id)sender {
    [self initNetworkCommunication];
    NSData *pictureData = UIImagePNGRepresentation([UIImage imageNamed:@"shalin.jpg"]);
    NSMutableData *mutedData = [[NSMutableData alloc] initWithData:pictureData];
    [outputStream write:[mutedData bytes] maxLength:[mutedData length]];
}

-(IBAction)testPicture:(id)sender {
    UIImage *image = [UIImage imageWithData:self.outputData];
    self.testImage.image = image
}

【问题讨论】:

  • 我们需要的不仅仅是不工作。你得到什么数据?有什么错误吗?
  • 很抱歉。我完全忘记指定错误。它显示了大约一半的图像,但其余部分是黑色的。
  • 我计算了每个实例中的字节数,发现当我在模拟器上运行它时,它传输了 244216 个字节,但在 iPhone 上它只传输了 131768 个字节。显然这是问题所在,但我仍然没有知道如何解决它。
  • 我想我解决了。我没有处理流的写作方面。我需要解决 NSStreamHasSpaceAvailable 案例。
  • 您能否发布您的解决方案作为后代的答案?

标签: ios objective-c networking twisted nsdata


【解决方案1】:

我找到了解决问题的方法。它与写入服务器时的可用空间有关。 iPhone 一次只能写入特定数量的字节,因此我必须通过 NSStreamEventHasSpaceAvailable 案例来调节写入委托的数据量。这是缺少的一段代码,它允许您将图像写入服务器并通过与扭曲服务器的 TCP 连接将其读回客户端:


缺少要放入 NSStream 委托的代码


case NSStreamEventHasSpaceAvailable:
        {
            if (self.appDel.willWrite && [self.appDel.inputData length] != 0) {
                int bufferSize = 1024;
                if ([self.appDel.inputData length] > bufferSize){
                    NSData *sendData = [self.appDel.inputData subdataWithRange:NSMakeRange(0, bufferSize)];
                    self.appDel.inputData = [[NSMutableData alloc] initWithData:[self.appDel.inputData subdataWithRange:NSMakeRange(bufferSize, [self.appDel.inputData length] - bufferSize)]];
                    [outputStream write:[sendData bytes] maxLength:[sendData length]];
                } else {
                    [outputStream write:[self.appDel.inputData bytes] maxLength:[self.appDel.inputData length]];
                    self.appDel.inputData = [[NSMutableData alloc] init];

                }
            }
        }

运行网络测试的修改版本


-(IBAction)runNetworkingTest:(id)sender {
    [self initNetworkCommunication];
    self.appDel.willWrite = YES;
    NSData *pictureData = UIImagePNGRepresentation([UIImage imageNamed:@"shalin.jpg"]);
    [self.appDel.inputData appendData:pictureData];
}

显示图片的代码


-(IBAction)showNetworkingArray:(id)sender {
    UIImage *image = [UIImage imageWithData:self.appDel.outputData];
    self.testImage.image = image;
}

注意:我一次写入 1024 个字节。如果您一次写入太多字节,它将无法正常工作。例如,我尝试了 1024 * 8 并且不适用于单个图像。但是,当我将缓冲区大小设置为 1024 时,我可以毫无问题地发送大约 10 张图像。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-02
    • 2019-08-03
    • 1970-01-01
    • 2014-04-24
    • 2015-01-08
    • 2017-10-24
    • 2016-05-02
    • 1970-01-01
    相关资源
    最近更新 更多