打开套接字,发送数据,关闭套接字=截断数据

时间:2011-05-30 22:43:56

标签: objective-c sockets ios4 flush

我无法在正在开发的iphone应用程序上的套接字上发送数据。 简而言之,我想连接到特定端口上的tcp服务器,发送数据有效负载然后关闭套接字。

在关闭之前,似乎套接字没有刷新等待缓冲区的数据。

这是我的代码:

int port = 1234;
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (CFStringRef)host, port, &readStream, &writeStream);
if (readStream && writeStream) {
    //CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
    CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);

    inputStream = (NSInputStream *)readStream;
    [inputStream retain];
    [inputStream setDelegate:self];
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [inputStream open];

    outputStream = (NSOutputStream *)writeStream;
    [outputStream retain];
    [outputStream setDelegate:self];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream open];
}

[outputStream write:(void *)&len maxLength:4];
[outputStream write:[data bytes] maxLength:[data length]];

if (inputStream) {
    CFReadStreamClose((CFReadStreamRef)inputStream);
    CFRelease(inputStream);
}
if (outputStream) {
    CFWriteStreamClose((CFWriteStreamRef)outputStream);
    CFRelease(outputStream);
}   

赞赏所有想法

1 个答案:

答案 0 :(得分:0)

您可以尝试等待CFWriteStreamGetStatus在关闭之前返回kCFStreamStatusAtEnd。我认为问题在于CFWriteStreamClose会自动从使用它的所有地方释放字符串,包括数据实际被推送到网络的位置,这意味着它在释放时会将未压缩的数据留在缓冲区中。这应该保证所有数据在刷新之前都已被推出。

http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFWriteStreamRef/Reference/reference.html