OS X / iOS& TCP:为什么CFSocketSendData在连接重置后调用时会崩溃应用程序?

时间:2017-04-30 19:24:20

标签: ios objective-c macos core-foundation

我使用类似于此的客户端代码:

#import <CoreFoundation/CFSocket.h>
#include <sys/socket.h>
#include <netinet/in.h>

void receiveData(CFSocketRef s, 
                         CFSocketCallBackType type, 
                         CFDataRef address, 
                         const void *data, 
                         void *info)
{
    CFDataRef df = (CFDataRef) data;
    int len = CFDataGetLength(df);
    if(len <= 0) return;

    CFRange range = CFRangeMake(0,len);
    UInt8 buffer[len];
    NSLog(@"Received %d bytes from socket %d\n", 
                  len, CFSocketGetNative(s));
    CFDataGetBytes(df, range, buffer);
    NSLog(@"Client received: %s\n", buffer); 
    NSLog(@"As UInt8 coding: %@", df);
}

int main ()
{
    CFSocketRef s = CFSocketCreate(NULL, PF_INET, 
                                            SOCK_STREAM, IPPROTO_TCP, 
                                            kCFSocketDataCallBack, 
                                            receiveData, 
                                            NULL);
    struct sockaddr_in      sin; 
    struct hostent           *host;

    host = gethostbyname("********");      
    memset(&sin, 0, sizeof(sin));
    memcpy(&(sin.sin_addr), host->h_addr,host->h_length); 
    sin.sin_family = AF_INET;
    sin.sin_port = htons(888);

    CFDataRef address, data;
    UInt8 message[] = "Hello world";
    CFRunLoopSourceRef source;

    address = CFDataCreate(NULL, (UInt8 *)&sin, sizeof(sin));
    data = CFDataCreate(NULL, message, sizeof(message));

    CFSocketConnectToAddress(s, address, 0);
    CFSocketSendData(s, NULL, data, 0);

    CFRelease(address);
    CFRelease(data);

    source = CFSocketCreateRunLoopSource(NULL, s, 0);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), 
                       source, 
                       kCFRunLoopDefaultMode);
    CFRelease(source);
    CFRelease(s);
    CFRunLoopRun(); 
}

它发送数据并得到正确的响应。但TCP不应该只发送数据,它应该发送数据可靠。

我测试了这样的年表:

  1. 客户来电CFSocketConnectToAddress
  2. 服务器授权客户端
  3. 但现在服务器应用程序进程崩溃了,服务器 - &gt;客户端发送RST标志。
  4. 之后,客户致电CFSocketSendData
  5. 我期望CFSocketSendData返回错误或至少抛出异常,但它会导致应用程序崩溃,@ try-catch不起作用。

1 个答案:

答案 0 :(得分:0)

你能尝试在第二个参数中使用显式地址吗?看看之后你是否收到错误。

CFSocketSendData(s ,, data,0);