OGeek|极客世界-中国程序员成长平台

标题: iphone - 通过 Socket 发送文件 (iOS) [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 11:49
标题: iphone - 通过 Socket 发送文件 (iOS)

我创建了一个基于 Socket 的简单聊天应用。 邮报:Socket Based iPhone App帮助我创建了这个。

我现在想通过套接字发送/接收文件。 请指点我如何实现这一目标。

干杯, 呸呸呸

编辑:

用于连接套接字的代码是:

NSString *aHostName = @"xx.xx.xx.xx";
NSInteger aPort = 1234;

CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)aHostName, aPort, &readStream, &writeStream);

self.inputStream = (NSInputStream *)readStream;
self.outputStream = (NSOutputStream *)writeStream;

[self.inputStream setDelegate:self];
[self.outputStream setDelegate:self];

[self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

[self.inputStream open];
[self.outputStream open];

用于发送数据的代码是

NSData *aData = [[NSData alloc] initWithData:[iRequestAPI dataUsingEncoding:NSASCIIStringEncoding]];
[self.outputStream write:[aData bytes] maxLength:[aData length]];
[aData release];

其中,iRequestAPI 是必须发送的字符串。

现在当我尝试通过套接字发送文件时,考虑到我将文件转换为 NSData 并使用 [self.outputStream write:[aData bytes] maxLength:[aData length]]; 可以由于连接带宽的原因,有可能无法发送整个文件。 如果没有发送整个文件,如何确保发送其余文件。

这是通过套接字发送文件的正确方法吗? 请建议..



Best Answer-推荐答案


如果你的 NSData 足够大,你需要把它切成小块。你需要字节来传输它们。例如:

NSData *newData = UIImagePNGRepresentation([UIImage imageNamed"Default.png"]);
    int index = 0;
    int totalLen = [newData length];
    uint8_t buffer[1024];
    uint8_t *readBytes = (uint8_t *)[newData bytes];

    while (index < totalLen) {
        if ([outputStream hasSpaceAvailable]) {
            int indexLen =  (1024>(totalLen-index))?(totalLen-index):1024;

            (void)memcpy(buffer, readBytes, indexLen);

            int written = [outputStream write:buffer maxLength:indexLen];

            if (written < 0) {
                break;
            }

            index += written;

            readBytes += written;
        }
    }

关于iphone - 通过 Socket 发送文件 (iOS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9432327/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4